我有一个JSON数组对象,如:
x= {"user":[{ "name": "Jhon", "age": "18" }, { "name": "Ted", "age": "20" }]};
我想将每个对象名称的每个值存储在一个简单的数组中,但我不知道该怎么做
我知道我可以使用JSON.parse(x)["user][0]["name"]
所以我需要如何获取对象数组中的对象数量:Objects.keys(JSON.parse(x)["users"]).length)
答案 0 :(得分:1)
Array#map()
const data = {"user":[{ "name": "Jhon", "age": "18" }, { "name": "Ted", "age": "20" }]};
console.log(data.user.map(u=>u.name));
答案 1 :(得分:0)
因此,您希望将用户数组(x.user)映射到新集合,只获取用户的名称。看看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map。
简而言之:
var x = {"user":[{ "name": "Jhon", "age": "18" }, { "name": "Ted", "age": "20" }]};
var y = x.user.map(user => user.name) // <-- y becomes Array [ "Jhon", "Ted" ]