从对象数组中获取值



那么,假设我有一个对象,在它里面,我有一个对象数组

let partys = {
"id": 241,
"name": "Rock Party",
"type": "party",
"days": [
{
"id": 201,
"day": "Monday"
},
{
"id": 202,
"dia": "Friday"
}
],
}

如何只获得"day"的值?这样的:

let days = ["Monday", "Friday"]

我已经使用了Object.values(party.days[0]),但是结果是

[201, 'Monday']

let partys = {
"id": 241,
"name": "Rock Party",
"type": "party",
"days": [
{
"id": 201,
"day": "Monday"
},
{
"id": 202,
"dia": "Friday"
}
],
};
let days = partys.days.map(x => x.dia || x.day);
console.log(days);

这是处理您的数据的代码。但我确实确信,属性的名称应该是daydia,而不是同时两者。

假设dia是一个错别字:

const days = [];
for (let p of partys.days) {
days.push(p.day);
}
console.log(days)

您可以轻松地使用Nullish合并运算符(??)

partys.days.map((x) => x.dia ?? x.day);

let partys = {
id: 241,
name: "Rock Party",
type: "party",
days: [
{
id: 201,
day: "Monday",
},
{
id: 202,
dia: "Friday",
},
],
};
let days = partys.days.map((x) => x.dia ?? x.day);
console.log(days);

相关内容

  • 没有找到相关文章

最新更新