Reputation: 80
I need to get an array of all the name
values from a JSON structure.
My JSON looks like this:
{
"profile": {
"G5j7": {
"name": "siddharth",
"age": "17"
},
"Loj9": {
"name": "ram",
"age": "20"
},
"Huy8": {
"name": "maix"
}
}
}
I can get a specific name
value by:
var singleName = profile.G5j7.name;
But how do I get an array of all the name
values if don't know all the IDs inside profile
? I need to store in a variable.
Upvotes: 1
Views: 3198
Reputation: 2531
You can do like this:
const names = Object.values(profile).map((profile) => profile.name);
Object.values()
returns an array of the values.
Then for each profile, use .map()
to get each name
.
Upvotes: 0
Reputation: 1185
let data = {
"profile":
{ "G5j7": { "name": "siddharth", "age": "17" },
"Loj9": { "name": "ram", "age": "20" },
"Huy8": { "name": "maix" }
}
};
for (const [key, value] of Object.entries(data.profile)) {
console.log(`${value.name}`);
}
Upvotes: 0
Reputation: 5613
You can use Object.keys
to get all properties keys in an Object, with that you can get access to all profile object keys with that you can retrieve name for each key like bellow
let data = {
"profile": {
"G5j7": {
"name": "siddharth",
"age": "17"
},
"Loj9": {
"name": "ram",
"age": "20"
},
"Huy8": {
"name": "maix"
}
}
};
let profiles_keys = Object.keys(data.profile);
let results = profiles_keys.reduce((accumulator, current)=> {
return accumulator.concat(data.profile[current].name)
}, []);
console.log(results);
Upvotes: 1
Reputation: 747
You can use Object.getOwnPropertyNames
. This function getting field names from in object to array.
let data = { "profile": { "G5j7": { "name": "siddharth", "age": "17" }, "Loj9": { "name": "ram", "age": "20" }, "Huy8": { "name": "maix" } } }
let propNames = Object.getOwnPropertyNames(data.profile)
propNames.forEach((propname) => { console.log(data.profile[propname].name) })
Upvotes: 1
Reputation: 3571
Object.values(yourObj.profile).map(v => v.name)
Object.values() returns an array of the values on every (own) prop of your object. So you can forget about the property names and iterate on its values
Upvotes: 1
Reputation: 3900
const decodedJsonObject = " { "profile": { "G5j7": { "name": "siddharth", "age": "17" }, "Loj9": { "name": "ram", "age": "20" }, "Huy8": { "name": "maix" } } }"
var singleName = profile.G5j7.name;
Upvotes: -2