Tewan
Tewan

Reputation: 171

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)

Upvotes: 0

Views: 2124

Answers (3)

Marcin Pevik
Marcin Pevik

Reputation: 173

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

Upvotes: 0

Douglas Tyler Gordon
Douglas Tyler Gordon

Reputation: 569

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"]; 
}

Upvotes: 0

Weedoze
Weedoze

Reputation: 13953

Array#map()

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

Upvotes: 1

Related Questions