如何循环JSON数组并获得特定值?

时间:2023-01-15 21:15:53

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

如何遍历下面的数组并得到“car1”的值?下面的代码返回未定义的

<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>

7 个解决方案

#1


0  

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:

x是对象键的字符串值。为了获得嵌套对象的car1属性,可以将循环改为:

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.

在使用forin循环时使用hasOwnProperty也是一种很好的实践,它还可以遍历对象的原型链中的属性。

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

#2


0  

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)

#3


0  

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.

这样您就可以通过myObj[cars]和myObj[cars2]对象属性进行迭代。

#4


0  

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)

car1属性不在你试图访问它的级别。遍历对象并检查下一层上是否存在car1。如果是,就显示警报。还要注意,在for循环中应该有一个if语句,以确保属性存在(或其他条件)

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);
    }

 }
}

#5


0  

<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;

#6


0  

You should just change the for loop to

您应该将for循环改为

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

Try it out

试试

#7


0  

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()

我们将使用对象。因为我们不需要键,所以要获取值的数组,然后使用array .prototype.filter()来过滤任何没有Object.prototype.hasownproperty()报告的“car1”属性的值,最后使用array .prototype.map()对其进行映射以转换。作为保持警报的一种方式,我们将使用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

现在我们有了对象中值的car1属性的数组。好消息是,如果给它一个对象数组而不是一个嵌套对象,那么它也可以工作,但这只是因为我们不关心保存对象的键,而只关心对象实际上拥有“car1”属性


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

可以重写,因为JavaScript函数是一阶的,可以作为参数传递给其他函数?

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

#1


0  

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:

x是对象键的字符串值。为了获得嵌套对象的car1属性,可以将循环改为:

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.

在使用forin循环时使用hasOwnProperty也是一种很好的实践,它还可以遍历对象的原型链中的属性。

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

#2


0  

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)

#3


0  

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.

这样您就可以通过myObj[cars]和myObj[cars2]对象属性进行迭代。

#4


0  

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)

car1属性不在你试图访问它的级别。遍历对象并检查下一层上是否存在car1。如果是,就显示警报。还要注意,在for循环中应该有一个if语句,以确保属性存在(或其他条件)

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);
    }

 }
}

#5


0  

<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;

#6


0  

You should just change the for loop to

您应该将for循环改为

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

Try it out

试试

#7


0  

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()

我们将使用对象。因为我们不需要键,所以要获取值的数组,然后使用array .prototype.filter()来过滤任何没有Object.prototype.hasownproperty()报告的“car1”属性的值,最后使用array .prototype.map()对其进行映射以转换。作为保持警报的一种方式,我们将使用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

现在我们有了对象中值的car1属性的数组。好消息是,如果给它一个对象数组而不是一个嵌套对象,那么它也可以工作,但这只是因为我们不关心保存对象的键,而只关心对象实际上拥有“car1”属性


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

可以重写,因为JavaScript函数是一阶的,可以作为参数传递给其他函数?

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