我有这个下面的对象结构,现在有3条记录作为示例。但是我们将拥有20多个记录。
{
"data": [{
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8770009prd",
"shortdescription": "<p>Hybrid Dual Injection Cover and a Tempered Glass.<\/p>",
"displayname": "Protection Essentials Bundle - Samsung Galaxy S9 (Clear) 822445132623"
}
},
{
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8530068prd",
"shortdescription": "String.class",
"displayname": "JBL UA Flex Headphones (Gray) - 050036342735"
}
}, {
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8630012prd",
"shortdescription": "<p>This slim case has everything you want - style and protection.<\/p>",
"displayname": "Otterbox Symmetry Series Case - Samsung Galaxy S9 (Clear) - 660543444121"
}
}
]
}
从上面的对象中,我需要在下面的数组中获取它。
identifierList = [ 'access8770009prd', 'access8530068prd', 'access8630012prd' ]
作为一维数组。任何人都可以提供一种有效的方法。
答案 0 :(得分:1)
如果a
是您拥有的json,则可以进行以下操作
identifierList = a.data.map(x => x.values.identifier)
答案 1 :(得分:0)
您可以将 map()与数组解构一起使用,以获取identifier
的数组。
var data = [{
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8770009prd",
"shortdescription": "<p>Hybrid Dual Injection Cover and a Tempered Glass.<\/p>",
"displayname": "Protection Essentials Bundle - Samsung Galaxy S9 (Clear) 822445132623"
}
},
{
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8530068prd",
"shortdescription": "String.class",
"displayname": "JBL UA Flex Headphones (Gray) - 050036342735"
}
}, {
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8630012prd",
"shortdescription": "<p>This slim case has everything you want - style and protection.<\/p>",
"displayname": "Otterbox Symmetry Series Case - Samsung Galaxy S9 (Clear) - 660543444121"
}
}
];
var identifierList = data.map(({values}) => values.identifier);
console.log(identifierList);
使用forEach()
var data = [{
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8770009prd",
"shortdescription": "<p>Hybrid Dual Injection Cover and a Tempered Glass.<\/p>",
"displayname": "Protection Essentials Bundle - Samsung Galaxy S9 (Clear) 822445132623"
}
},
{
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8530068prd",
"shortdescription": "String.class",
"displayname": "JBL UA Flex Headphones (Gray) - 050036342735"
}
}, {
"datatype": "AccessoryProduct",
"values": {
"identifier": "access8630012prd",
"shortdescription": "<p>This slim case has everything you want - style and protection.<\/p>",
"displayname": "Otterbox Symmetry Series Case - Samsung Galaxy S9 (Clear) - 660543444121"
}
}
];
var identifierList = [];
data.forEach(({values}) => identifierList.push(values.identifier));
console.log(identifierList);