I am new to JavaScript I am trying to combine two object from two arrays
First Array
const TESTARRAY = [{
id: 3,
parameter1: 'x',
parameter2: 'y',
parameter3: 'z'
}, {
id: 1,
parameter1: 'u',
parameter2: 'v',
parameter3: 'w'
}, {
id: 5,
parameter1: 'q',
parameter2: 'w',
parameter3: 'e'
}]
Second array
var json = [{
name: 'aaa'
}, {
name: 'ccc'
}, {
name: 'bbb'
}];
Expected Output
[{
additional: "aaa",
id: 3,
parameter1: "x",
parameter2: "y",
parameter3: "z"
}, {
additional: "ccc",
id: 1,
parameter1: "u",
parameter2: "v",
parameter3: "w"
}, {
additional: "bbb",
id: 5,
parameter1: "q",
parameter2: "w",
parameter3: "e"
}]
Code I tried below in JSFiddle I try to loop the var and add the element to TESTARRAY but I am getting same value "bbb" anyone can guide me for better approach?
const TESTARRAY = [{
id: 3,
parameter1: 'x',
parameter2: 'y',
parameter3: 'z'
}, {
id: 1,
parameter1: 'u',
parameter2: 'v',
parameter3: 'w'
}, {
id: 5,
parameter1: 'q',
parameter2: 'w',
parameter3: 'e'
}]
var json = [{
name: 'aaa'
}, {
name: 'ccc'
}, {
name: 'bbb'
}];
for (var key in json) {
if (json.hasOwnProperty(key)) {
TESTARRAY.map(i => i.additional = json[key].name)
}
}
console.log(TESTARRAY)
-
You don't have JSON. You have plain objects and plain arrays. JSON is a text serialisation format similar to XML. It will always be represented as a string.VLAZ– VLAZ2020年08月12日 05:56:13 +00:00Commented Aug 12, 2020 at 5:56
-
Just loop and update same index of the array for (const [k, v] of json.entries()) {TESTARRAY[k]['additional'] = v.name;}Arjun J Gowda– Arjun J Gowda2020年08月12日 06:02:51 +00:00Commented Aug 12, 2020 at 6:02
3 Answers 3
You could map a new array with merged properties of the second array at the same index.
const
array1 = [{ name: 'aaa' }, { name: 'ccc' }, { name: 'bbb' }],
array2 = [{ id: 3, parameter1: 'x', parameter2: 'y', parameter3: 'z' }, { id: 1, parameter1: 'u', parameter2: 'v', parameter3: 'w' }, { id: 5, parameter1: 'q', parameter2: 'w', parameter3: 'e' }],
merged = array1.map(({ name: additional }, i) => ({ additional, ...array2[i] }));
console.log(merged);
.as-console-wrapper { max-height: 100% !important; top: 0; }
1 Comment
Assuming the two arrays you want to combine are the same size. You can simply do something like this.
for (let i = 0; i < TESTARRAY.length; ++i)
{
TESTARRAY[i] = {...json[i], ...TESTARRAY[i]};
}
1 Comment
map second argument is an index of the current item, you can use that to reference your json variable.
const TESTARRAY = [{
id: 3,
parameter1: "x",
parameter2: "y",
parameter3: "z"
},
{
id: 1,
parameter1: "u",
parameter2: "v",
parameter3: "w"
},
{
id: 5,
parameter1: "q",
parameter2: "w",
parameter3: "e"
}
];
var json = [{
name: "aaa"
},
{
name: "ccc"
},
{
name: "bbb"
}
];
const newTestArray = TESTARRAY.map((curr, index) => ({
additional: json[index].name,
...curr
}));
console.log(newTestArray);
Comments
Explore related questions
See similar questions with these tags.