gpt4 book ai didi

javascript - 遍历对象,其中值是对象数组,并从对象数组的每个对象返回一个值

转载 作者:行者123 更新时间:2023-11-30 13:46:06 25 4
gpt4 key购买 nike

如何从中获取所有 office 值并将其存储为简单数组?

var data = {
'XYZ': [{
office: 'xyz.in',
reportName: 'payroll',
event: 'open',
timestamp: '02-12-2019 00:15:29'
},
{
office: 'xyz.in',
reportName: 'payroll',
event: 'processed',
timestamp: '02-12-2019 00:15:32'
}
],
'yyy': [{
office: 'yyy.in',
reportName: 'payroll',
event: 'delivered',
timestamp: '02-12-2019 00:15:29'
},
{
office: 'yyy.in',
reportName: 'payroll',
event: 'open',
timestamp: '02-12-2019 00:15:32'
}
],
'zzz': [{
office: 'xyz.in',
reportName: 'payroll',
event: 'delivered',
timestamp: '02-12-2019 00:15:29'
},
{
office: 'xyz.in',
reportName: 'payroll',
event: 'open',
timestamp: '02-12-2019 00:15:32'
}
]
}

输出应该是这样的:

officesArray = ['xyz.in', 'yyy.in', 'xyz.in']

我的代码是

var Office = (Object.entries(grpDatas).flatMap(([k, v]) => (v.forEach(({office})=> office))))

它打印array of undefined

最佳答案

使用 map 而不是 forEach 并且您正在访问 email 而不是 office:

var data = {
'XYZ': [{
office: 'xyz.in',
reportName: 'payroll',
event: 'open',
timestamp: '02-12-2019 00:15:29'
},
{
office: 'xyz.in',
reportName: 'payroll',
event: 'processed',
timestamp: '02-12-2019 00:15:32'
}
],
'yyy': [{
office: 'yyy.in',
reportName: 'payroll',
event: 'delivered',
timestamp: '02-12-2019 00:15:29'
},
{
office: 'yyy.in',
reportName: 'payroll',
event: 'open',
timestamp: '02-12-2019 00:15:32'
}
],
'zzz': [{
office: 'xyz.in',
reportName: 'payroll',
event: 'delivered',
timestamp: '02-12-2019 00:15:29'
},
{
office: 'xyz.in',
reportName: 'payroll',
event: 'open',
timestamp: '02-12-2019 00:15:32'
}
]
}

var Email = Object.values(data).flatMap(item => [...new Set(item.map(({office})=> office))])
console.log(Email)

关于javascript - 遍历对象,其中值是对象数组,并从对象数组的每个对象返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59308668/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com