简体   繁体   中英

How to loop through JSON array and get specific values

How can I loop through the array below and get the values of "car1"? The code below returns undefined

<script>
var myObj = {
  "cars": {
    "car1":"Ford",
    "car2":"BMW",
    "car3":"Fiat"
  },
  "cars2": {
    "car1":"Ford2",
    "car2":"BMW2",
    "car3":"Fiat2"
  }
}

for (x in myObj) {
 alert(x.car1);
}

</script>

For aggregating those values into an array, for example:

  let aggregated = []; var myObj = { "cars": { "car1":"Ford", "car2":"BMW", "car3":"Fiat" }, "cars2": { "car1":"Ford2", "car2":"BMW2", "car3":"Fiat2" } } Object.keys(myObj).forEach(e => { aggregated.push(myObj[e].car1) }) console.log(aggregated) 

If you have any other object inside and you want to get access to their properties too, you can create nested loop, like this:

 var myObj = { "cars": { "car1":"Ford", "car2":"BMW", "car3":"Fiat" }, "cars2": { "car1":"Ford2", "car2":"BMW2", "car3":"Fiat2" } } // Iterate over the first level for (x in myObj) { // Iterate over the second level for (y in myObj[x]) { document.getElementById("demo").innerHTML += myObj[x][y] + "<br>"; } } 
 <div id="demo"></div> 

This way you will be able to iterate through myObj[cars] and myObj[cars2] object properties too.

in your loop:

for (x in myObj) {
 alert(x.car1);
}

x is the string value of key of your object. In order to get the car1 property of your nested object you can change your loop as:

for (x in myObj) {
 alert(myObj[x].car1);
}

It is also a good practice to use hasOwnProperty while using for-in loop it might also iterate over properties which are in your object's prototype chain.

for (x in myObj) {
 if (myObj.hasOwnProperty(x)) {
   alert(myObj[x].car1);
 }
}

Your car1 property isn't at the level that you're trying to access it at. Loop through the object and check to see if car1 exists on the next level down. If it does, show the alert. Also note, you should have an if statement in your for in loop to make sure the property exists (or some other condition)

 var myObj = { "cars": { "car1":"Ford", "car2":"BMW", "car3":"Fiat" }, "cars2": { "car1":"Ford2", "car2":"BMW2", "car3":"Fiat2" } } for (var x in myObj) { if (myObj.hasOwnProperty(x)) { var obj = myObj[x]; if (obj.hasOwnProperty('car1')) { alert(obj.car1); } } } 

<script>
    var myObj = {
        "cars": {
            "car1": "Ford",
            "car2": "BMW",
            "car3": "Fiat"
        },
        "cars2": {
            "car1": "Ford2",
            "car2": "BMW2",
            "car3": "Fiat2"
        }
    }

    var res = Object.values(myObj)
        .map(i => i.car1)
        .filter(name => (name !== 'Ford2'));

    document.getElementById("demo").innerHTML = res;

You should just change the for loop to

for (x in myObj) alert(myObj[x].car1);

Try it out

You have a small misgiving here. You're not looping over an Array, you are looping over the properties of an Object with a for...in loop.

You should be careful with that. You probably want to make it 'safe'(won't traverse the prototype or non enumerable properties) by changing to a more updated methods of traversal. Namely safely getting the values of the object, not the keys and then looping over it with some of the newer looping functions.

We'll be using Object.values to get an array of the values since we don't need the keys, then Array.prototype.filter() to filter out anything without a 'car1' property as reported by Object.prototype.hasownproperty() , and finally mapping over it to transform it with Array.prototype.map() . As a way to keep the alerts in, we will then be alerting on each of them using Array.prototype.forEach()

Object
  .values(myObj) // since we don't care about the keys, only loop over the values
  .filter(obj => // filter out any values without a 'car1' property
    obj.hasOwnProperty('car1') 
  )
  .map(obj => obj.car1) // de-nest the car1 property
  .forEach(alert)

Now we have an array of the car1 properties of the values in the Object. The good news is this will work if given an Array of objects as well instead of a nested Object, but only because we don't care about the keys that hold the objects and only that an object actually has a 'car1' property


Tricks used for brevity

Arrow Functions

function (a,b){ return console.log(a,b) }

can be rewritten as

(a,b) => console.log(a,b)

Direct function reference

[1,2,3].forEach(item => alert(item))

can be rewritten since in JavaScript functions are first order and can be passed as arguments to other functions

[1,2,3].forEach(alert)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM