简体   繁体   中英

How to store key values of a JSON array of object in an array

I've got a JSON array of objects like :

x= {"user":[{ "name": "Jhon", "age": "18" }, { "name": "Ted", "age": "20" }]};

I would like to store every values of names of each object in a simple array but I don't know how to do that

I know that I can get values of names with JSON.parse(x)["user][0]["name"]

So I need how to get the number of objects in my array of objects : Objects.keys(JSON.parse(x)["users"]).length)

Array#map()

 const data = {"user":[{ "name": "Jhon", "age": "18" }, { "name": "Ted", "age": "20" }]}; console.log(data.user.map(u=>u.name)); 

You can iterate over an array using the map function which takes a callback, and return exactly which property you want from each user object inside the callback. You'll be left with an array of names.

const myObject = {"user":[{ "name": "Jhon", "age": "18" }, { "name": "Ted", "age": "20" }]};
const names = myObject["user"].map((user) => {
    return user["name"]; 
}

So you want to map the array of users (x.user) to new collection, getting only the names of the user. Take a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map .

In short:

var x = {"user":[{ "name": "Jhon", "age": "18" }, { "name": "Ted", "age": "20" }]};

var y = x.user.map(user => user.name)  // <-- y becomes Array [ "Jhon", "Ted" ]

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