5

Consider I have an array

let array1 = [{a:1, b:2}, {e:5,f:6}]
let json1 = {c:3, d:4}

I want to append json1 to first item of array1 so the resultant looks like

array1 = [{a:1, b:2, c:3, d:4}, {e:5, f:6}]

I am sure push doesn't work here. I am not sure how to proceed further.

Mamun
  • 66,969
  • 9
  • 47
  • 59

6 Answers6

5

You can use spread operator

let array1 = [{a:1, b:2}, {e:5,f:6}];
let json1 = {c:3, d:4};
array1[0] = {...array1[0], ...json1};
console.log(array1);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
3

You could assign the new data to the object.

let array = [{ a: 1, b: 2 }, { e: 5, f: 6 }],
    data = { c: 3, d: 4 };

Object.assign(array[0], data);

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
2

You can try using Object.assign():

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object.

let array1 = [{a:1, b:2}, {e:5,f:6}]
let json1 = {c:3, d:4}
Object.assign(array1[0], json1);
console.log(array1);
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

Iterate using map and capture the first index and using the spread operator merge the json object with the first index.

let array1 = [{a:1, b:2}, {e:5,f:6}]
let json1 = {c:3, d:4}

let res = array1.map((obj, i) => (i === 0 ? {...obj, ...json1} : obj));

console.log(res);
Sajeeb Ahamed
  • 6,070
  • 2
  • 21
  • 30
0

Loop through json1 with Object.keys() and add the key value pairs:

let array1 = [{a:1, b:2}, {e:5,f:6}]
let json1 = {c:3, d:4}

Object.keys(json1).forEach(ent => {
    array1[0][ent] = json1[ent]
})

console.log(array1)
symlink
  • 11,984
  • 7
  • 29
  • 50
0

If you want to assign alphabetically, you can use the char code

let array1 = [{a:1, b:2}, {e:5,f:6}];
let json1 = {c:3, d:4};

const getCodeStartEnd = (obj) => {
    const keys = Object.keys(obj);
    return [keys.shift().charCodeAt(0), keys.pop().charCodeAt(0)];
};

const [start, end] = getCodeStartEnd(json1);
const res = [];

for (const j of array1) {
    const [f, l] = getCodeStartEnd(j);
    if (l + 1 === start) {
        res.push({...j, ...json1});
        continue;
    }
    res.push(j)
}

console.log(res);
baao
  • 71,625
  • 17
  • 143
  • 203