I'm new to JS and trying to figure out how to iterate through a json array and return only a subset of elements. Specifically I would like to know how to return only the 'first_name' and 'last_name' from the Mock data in the attached code snippet. It seems like it should be straightforward but I'm scratching my head.
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"[email protected]","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"[email protected]","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"[email protected]","country":"Nicaragua"}]
people.forEach(person => {
for (let key in person) {
console.log(`${key} => ${person[key]}`);
}
CodePudding user response:
Use the element names
people.forEach(person => {
console.log(JSON.stringify(person) "\n");
console.log(person["first_name"], person["last_name"], "\n");
});
Produces this output:
{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"[email protected]","country":"Indonesia"}
Talbert Kohnert
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"[email protected]","country":"Sweden"}
Ruthie McKleod
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"[email protected]","country":"Nicaragua"}
Lenore Foister
CodePudding user response:
you can achieve this by using the map function.
map lets you iterate over each item in the array and return a new value for each iteration while returning a new array, so for your case:
let people = [
{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"[email protected]","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"[email protected]","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"[email protected]","country":"Nicaragua"}
]
const newArray = people.map((person) => {
return {
first_name: person.first_name,
last_name: person.last_name
}
})
console.log(newArray)
here you get a new array with just the properties you need.
CodePudding user response:
There are numerous way of achieving this output. One of most frequently used method is using map()
of es6.
let people = [{"id":1,"first_name":"Talbert","last_name":"Kohnert","email":"[email protected]","country":"Indonesia"},
{"id":2,"first_name":"Ruthie","last_name":"McKleod","email":"[email protected]","country":"Sweden"},
{"id":3,"first_name":"Lenore","last_name":"Foister","email":"[email protected]","country":"Nicaragua"}]
//by map method
people.map((person,index)=>{
console.log(`${person.first_name} ${person.last_name}`)
})
// by forEach
people.forEach(person => {
console.log(`${person.first_name} ${person.last_name}`)
}