0

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)

1
  • What exactly don't you know how to do? Show your progress so far. Commented May 11, 2017 at 14:07

3 Answers 3

1
Array#map()

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.