gpt4 book ai didi

Javascript 如何让 .map() 返回新数组及其初始文本属性而不是编号索引?

转载 作者:行者123 更新时间:2023-11-30 23:55:40 26 4
gpt4 key购买 nike

我正在尝试展平对象的嵌套数组。

我有以下数组:

array = [
{
id: 123,
name: 'Peter',
phone: '',
addresses:
[
{
address1: 'Manchester, UK', address2: 'London, UK'
},
{
address1: 'Liverpool, UK', address2: 'NY, USA'
}
]
},
{
id: 124,
name: 'Sara',
phone: '',
addresses: [{ address1: 'London, UK', address2: 'Paris, FR' }]
}
];

所需的输出应该是这样的:

array = [
{
id: 123,
name: 'Peter',
phone: '',
addresses_address1: 'Manchester, UK',
addresses_address2: 'London, UK'
},
{
id: 124,
name: 'Sara',
phone: '',
addresses_address1: 'London, UK',
addresses_address2: 'Paris, FR'
}
];

我使用了.map.reduce函数,示例取自this site :

var flatten = function (data) {
return data.reduce(function iter(r, a) {
if (typeof a === 'object') {
return Object.keys(a).map(k => a[k]).reduce(iter, r);
}
return r.concat(a)
}, []);
}
console.log(flatten(this.array))

但是它不是获取带有文本属性 id name... 的数组,而是返回索引 0, 1 ...

enter image description here

这是一个stackblitz .

最佳答案

您可以将索引作为属性的一部分,并为外部数组的每个元素返回一个新对象。

function flat(object, path = []) {
return object && typeof object === 'object'
? Object
.entries(object)
.reduce((r, [k, v]) => ({ ...r, ...flat(v, [...path, k]) }), {})
: { [path.join('-')]: object };
}

var array = [{ id: 123, name: 'Peter', phone: '', addresses: [{ address1: 'Manchester, UK', address2: 'London, UK' }, { address1: 'Liverpool, UK', address2: 'NY, USA' }] }, { id: 124, name: 'Sara', phone: '', addresses: [{ address1: 'London, UK', address2: 'Paris, FR' }] }],
result = array.map(o => flat(o));

console.log(result);

关于Javascript 如何让 .map() 返回新数组及其初始文本属性而不是编号索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61078613/

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