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>
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>
Share
Improve this question
asked Jun 20, 2018 at 21:52
YWSWYWSW
1331 gold badge1 silver badge4 bronze badges
5
- Possible duplicate of From an array of objects, extract value of a property as array – Heretic Monkey Commented Jun 20, 2018 at 22:00
-
Do
console.log( x )
inside the loop – Ben West Commented Jun 20, 2018 at 22:01 -
Object.values(myObj).forEach(i => console.log(i.car1))
– Keith Commented Jun 20, 2018 at 22:01 - Object.keys(myObj).forEach(key => alert(myObj[key].car1)) – ramiz4 Commented Jun 20, 2018 at 22:03
-
1
Always read the documentation of syntax you are not familiar with, do not assume. Read about
for...in
. – Felix Kling Commented Jun 20, 2018 at 22:06
7 Answers
Reset to default 2in 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);
}
}
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.
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)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744195550a4562640.html
评论列表(0条)