How to get the value of a property in an array of JSON objects?

1

I have an array of objects and I want to get [152,153,154,155,156,157] which are the values for the intento property of each object. I would get it by going through for , but I want to know if there is a function to make it easier.

let arr= [{intento: 152, tipo: "intruso"},
 {intento: 153, tipo: "intruso"},
 {intento: 154, tipo: "intruso"},
 {intento: 155, tipo: "intruso"},
 {intento: 156, tipo: "intruso"},
 {intento: 157, tipo: "intruso"}]
 
 let copy=[];
 for(let i=0; i<arr.length; i++){
 copy.push(arr[i].intento);
 }
 console.log(copy);
    
asked by hubman 22.11.2018 в 15:56
source

4 answers

6

There is a more elegant way to get it, but I think it is not much more efficient than the for. Anyway, I'll give you the proposal:

let arr= [{intento: 152, tipo: "intruso"},
 {intento: 153, tipo: "intruso"},
 {intento: 154, tipo: "intruso"},
 {intento: 155, tipo: "intruso"},
 {intento: 156, tipo: "intruso"},
 {intento: 157, tipo: "intruso"}]
 let resultado = arr.map(a => a.intento)
console.log(resultado);

As you see in a single line you get the same result as the for, but I do not know if it is faster or not.

    
answered by 22.11.2018 / 16:02
source
3

If you use jQuery you can do it using "map", but I think that a for cycle would be the best.

let arr = [
 {intento: 152, tipo: "intruso"},
 {intento: 153, tipo: "intruso"},
 {intento: 154, tipo: "intruso"},
 {intento: 155, tipo: "intruso"},
 {intento: 156, tipo: "intruso"},
 {intento: 157, tipo: "intruso"}]
 
var res = $.map(arr, function( val, i ) { return val.intento; });

console.log(res);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Good luck!

    
answered by 22.11.2018 в 16:02
2

Perform it with a forEach() in this way

let data =[{intento: 152, tipo: "intruso"},
 {intento: 153, tipo: "intruso"},
 {intento: 154, tipo: "intruso"},
 {intento: 155, tipo: "intruso"},
 {intento: 156, tipo: "intruso"},
 {intento: 157, tipo: "intruso"}]


data.forEach((element, index) => {
  console.log(element["intento"])
})

You will simply need to tell the function that goes inside 2 arguments: element e index later in the console.log () you indicate that you only want the value in intento in this way element["nombredelaclave"]

In the long run forEach ends up being faster than map and in fact the latter generates a new arrangement starting from the previously created and I think that's not what you need

    
answered by 22.11.2018 в 16:06
0

And to put another option ... I put the for of of ES6

let arr= [{intento: 152, tipo: "intruso"},
 {intento: 153, tipo: "intruso"},
 {intento: 154, tipo: "intruso"},
 {intento: 155, tipo: "intruso"},
 {intento: 156, tipo: "intruso"},
 {intento: 157, tipo: "intruso"}]
 
let copy = [];
 
for (let item of arr) {
   copy.push(item.intento);
}

console.log(copy);
    
answered by 22.11.2018 в 16:42