我有一个多维数组。我想要添加没有任何键值的Id。我想要一个关键值,如" 566934ae-879a-58cb"我该如何获得该ID?在javascript中。
var data = [{
"7acafaa5-f276-9094": {
"name": "kaa",
"number": "46645",
"city": "Surat",
"hobby": "hockey",
"birthdate": "2017-06-21"
},
"566934ae-879a-58cb": {
"name": "Karrgi",
"number": "096013",
"city": "Ahmedabad",
"hobby": "hockey",
"birthdate": "2017-06-15"
},
"365867ca-9f09-367b": {
"name": "Karnaargi",
"number": "06013",
"city": "Ahmedabad",
"hobby": "hockey",
"birthdate": "2017-06-15"
}
}
]
我必须从数组中获取所有id(键),这些ID都添加在一个表中
答案 0 :(得分:3)
您可以使用Object.keys()
,因为对象是一个数组使用索引来访问数组元素,那么可以使用该方法。
console.log(Object.keys(data[0]))
var data = [{
"7acafaa5-f276-9094": {
"name": "kaa",
"number": "46645",
"city": "Surat",
"hobby": "hockey",
"birthdate": "2017-06-21"
},
"566934ae-879a-58cb": {
"name": "Karnav B Pargi",
"number": "09601096013",
"city": "Ahmedabad",
"hobby": "hockey",
"birthdate": "2017-06-15"
},
"365867ca-9f09-367b": {
"name": "Karnav B Pargi",
"number": "09601096013",
"city": "Ahmedabad",
"hobby": "hockey",
"birthdate": "2017-06-15"
}
}];
console.log(Object.keys(data[0]))

答案 1 :(得分:0)
您可以使用缩减功能并收集密钥并创建地图,以便您可以使用这些密钥来获取该数据。
var data = [{
"7acafaa5-f276-9094": {
"name": "kaa",
"number": "46645",
"city": "Surat",
"hobby": "hockey",
"birthdate": "2017-06-21"
},
"566934ae-879a-58cb": {
"name": "Karnav B Pargi",
"number": "09601096013",
"city": "Ahmedabad",
"hobby": "hockey",
"birthdate": "2017-06-15"
},
"365867ca-9f09-367b": {
"name": "Karnav B Pargi",
"number": "09601096013",
"city": "Ahmedabad",
"hobby": "hockey",
"birthdate": "2017-06-15"
}
}];
var idToProfileMap = data.reduce((acc, val) => {
const keys = Object.keys(val);
keys.forEach(k => {
acc[k] = val[k];
})
return acc;
}, {});
// get all keys
const allIds = Object.keys(idToProfileMap);
console.log(Object.keys(idToProfileMap));
// get data using the first key
console.log(idToProfileMap[allIds[0]])
如果数据有多个元素,上面的代码也可以使用。
答案 2 :(得分:0)
循环遍历data
数组以获取特定的id数据,然后遍历id对象以获取它的属性
var data = [{
"7acafaa5-f276-9094": {
"name": "kaa",
"number": "46645",
"city": "Surat",
"hobby": "hockey",
"birthdate": "2017-06-21"
},
"566934ae-879a-58cb": {
"name": "Karnav B Pargi",
"number": "09601096013",
"city": "Ahmedabad",
"hobby": "hockey",
"birthdate": "2017-06-15"
},
"365867ca-9f09-367b": {
"name": "Karnav B Pargi",
"number": "09601096013",
"city": "Ahmedabad",
"hobby": "hockey",
"birthdate": "2017-06-15"
}
}
];
data.forEach(function(id){
// Get the data of particular id. You can loop over the specific id to access it's properties
Object.keys(id).forEach(function(prop){
console.log(id[prop]);
})
})