我有这个对象数组
const relationData = [
{
kids: [
{ text: 'Newborn', value: 'newborn' },
{ text: 'For under 5\'s', value: 'under5' },
{ text: 'Teenagers', value: 'teenagers' }
]
},
我如何在此处访问kids
这个词?我想查看myvalue ==
孩子们的身份吗?
我尝试过:
for (var key in data) {
console.log(key);
}
但这似乎只给我一个索引
PS我不想提出这个词KIDS
因为我可以恢复它
答案 0 :(得分:0)
if('kids' in relationData[0]) {
//if key exists, do this
}
else {
//if key does not exist, do this
}
查看https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
答案 1 :(得分:0)
如果你想迭代数组并访问你应该做的每个孩子的价值:
for (let x = 0; x < relationalData.length; x++){
for (let y = 0; y < relationalData[x].kids.length; y++) {
console.log(relationalData[x].kids[y].value
}
}
请记住,根据您的数据结构,您有两个数组:
如果要访问relationalData中每个对象的键,您应该
Object.keys(relationalData[x])
答案 2 :(得分:0)
您可以在relationData中循环遍历每个obj的键,如下所示
for (var index in relationData) {
var keys = Object.keys(relationData[index]);
console.log(keys.indexOf("kids") > -1)// then relationData has an object with a key of "kids"
}
“kids”也可以是变量,因此您可以将其与其他键名重复使用