Shayne David
Shayne David

Reputation: 77

Add element in object in array loop

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)

Upvotes: 0

Views: 88

Answers (3)

Nina Scholz
Nina Scholz

Reputation: 386868

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; }

Upvotes: 3

bertdida
bertdida

Reputation: 5298

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);

Upvotes: 1

polcats
polcats

Reputation: 154

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]};
}

Upvotes: 2

Related Questions