JavaScriptのキーで2つのオブジェクトを結合する
次のようなオブジェクトの子と親のJSON配列が2つあるとします-
const child = [{
id: 1,
name: 'somename',
parent: {
id: 2
},
},
{
id: 2,
name: 'some child name',
parent: {
id: 4
}
}];
const parent = [{
id: 1,
parentName: 'The first',
child: {}
},
{
id: 2,
parentName: 'The second',
child: {}
},
{
id: 3,
parentName: 'The third',
child: {}
},
{
id: 4,
parentName: 'The fourth',
child: {}
}]; これら2つの配列を取り込むJavaScript関数を作成する必要があります。
そして、この関数は子配列オブジェクトを対応する親オブジェクトにマージする必要があります。
したがって、最終的な出力は次のようになります-
const output = [
{
id: 1,
parentName: The first,
child: {}
},
{
id: 2,
parentName: The second,
child: {
id: 1,
name: somename,
}
},
{
id: 3,
parentName: The third,
child: {}
},
{
id: 4,
parentName: The fourth,
child: {
id: 2
name: some child name,
}
},
]; 例
このためのコードは-
になりますconst child = [{
id: 1,
name: 'somename',
parent: {
id: 2
},
},
{
id: 2,
name: 'some child name',
parent: {
id: 4
}
}];
const parent = [{
id: 1,
parentName: 'The first',
child: {}
},
{
id: 2,
parentName: 'The second',
child: {}
},
{
id: 3,
parentName: 'The third',
child: {}
},
{
id: 4,
parentName: 'The fourth',
child: {}
}];
const combineParentChild = (parent, child) => {
const combined = [];
for (let i = 0; i < parent.length; i++) {
for (let j = 0; j < child.length; j++) {
if (child[j].parent.id === parent[i].id) {
parent[i].child.id = child[j].id;
parent[i].child.name = child[j].name;
break;
};
};
combined.push(parent[i])
};
return combined;
};
console.log(combineParentChild(parent, child)); 出力
そして、コンソールの出力は-
になります[
{ id: 1, parentName: 'The first', child: {} },
{
id: 2,
parentName: 'The second',
child: { id: 1, name: 'somename' }
},
{ id: 3, parentName: 'The third', child: {} },
{
id: 4,
parentName: 'The fourth',
child: { id: 2, name: 'some child name' }
}
] -
JavaScriptで2つの配列を結合する方法は?
以下は、JavaScriptで2つの配列を結合するコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> &
-
2つのJavaScriptオブジェクトをマージする方法は?
以下は、2つのJavaScriptオブジェクトをマージするコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> &nbs