gpt4 book ai didi

javascript - 如何在 Javascript 上动态交叉交叉合并那些 JSON 数组?

转载 作者:行者123 更新时间:2023-11-30 14:25:19 24 4
gpt4 key购买 nike

var a = [
{id:'1', age:18, name:'Jaden'},
{id:'2', age:19, name:'Mark'},
{id:'3', age:38, name:'Jackson'}
];

var b = [
{id:'1', job: 'webDev'},
{id:'1', job: 'webDev2'},
{id:'2', job: 'CEO'}
];

var c = [
{id:'1', birth: '2000/02/01'},
{id:'2', birth: '1999/05/12'},
{id:'3', birth: '1982/05/12'}
];

我想做喜欢的结果..

=====================结果========================

[

{id:'1', age:10, name:'Jaden', job: 'webDev', birth: '1998/02/01'},
{id:'1', age:10, name:'Jaden', job: 'webDev2', birth: '1998/02/01'},
{id:'2', age:15, name:'Mark', job: 'CEO', birth: '2000/05/12'},
{id:'3', age:38, name:'Jackson', job: '', birth: '1982/05/12'}

]

我已经尝试了一整天,但我仍然没有找到任何解决方案:(它不是 Join,'Key' 是 id。

最佳答案

您可以使用一个临时数组来收集所有属性,方法是用对象减少给定的数组。

这个提议是一个抽象的解决方案,这意味着除了常见的 id 之外,它不限于某些给定的其他属性。所有其他属性都在事先不知道的情况下进行处理。

var a = [{ id: '1', age: 18, name:'Jaden' }, { id: '2', age: 19, name: 'Mark' }, { id: '3', age: 38, name: 'Jackson' }],
b = [{ id: '1', job: 'webDev' }, { id: '1', job: 'webDev2' }, { id: '2', job: 'CEO' }],
c = [{ id: '1', birth: '2000/02/01' }, { id: '2', birth: '1999/05/12'}, { id: '3', birth: '1982/05/12' }],
result = [a, b, c].reduce((r, a) => {
var temp = [],
template = Object.assign(...Object.keys(a[0]).filter(k => k !== 'id').map(k => ({ [k]: '' })));
a.forEach(o => {
var t = r.filter(({ id }) => o.id === id);
temp.push(...(t.length ? t : [{ id: o.id }]).map(p => Object.assign({}, p, template, o)));
});
temp.push(...r
.filter(({ id }) => !temp.some(t => t.id === id))
.map(p => Object.assign({}, p, template))
);
return temp;
}, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何在 Javascript 上动态交叉交叉合并那些 JSON 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52039840/

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