-2

How can I assign key value from array of object to another array object

I would like to assign the key:value pair to the existing array of object from the another array of objects.

I have check this thread but it is not working in my case.

I have tried something like this but that is not returning the desired output that I am looking for.

const DataA = {
  "id": 57,
  "status": true,
  "options": [{ "id": 1, "name": "Type A" },
    { "id": 2, "name": "Type B" },
    { "id": 3, "name": "Type C" }]
}

const DataB = {
  "id": 57,
  "status": true,
  "options": [{ "id": 1, "value": 10 },
    { "id": 2, "value": 20 },
    { "id": 3, "value": 30 }]
}

let result;
var A1 = DataA.options.map((v) => {
  console.log(v);
  result = v;
})

var A2 = DataB.options.map(v => {
  result.options = v;
  console.log("result",result);
})

let arr3 = DataA.options.map((item, i) => Object.assign({}, item, DataB[i]));

console.log(arr3);

Result will be I need as below:

const DataA = {
  "id": 57,
  "status": true,
  "options": [{ "id": 1, "name": "Type A", "value": 10 },
    { "id": 2, "name": "Type B", "value": 20 },
    { "id": 3, "name": "Type C", "value": 30 }]
}

I need to merge the deep clone of the array that is slightly different from this thread.

TMA
  • 1,419
  • 2
  • 22
  • 49
  • Does this answer your question? [Merge two array of objects based on a key](https://stackoverflow.com/questions/46849286/merge-two-array-of-objects-based-on-a-key) – pilchard Apr 02 '21 at 09:38
  • No, as I would like to do a deep merge of array. – TMA Apr 02 '21 at 09:55

1 Answers1

1

The linked duplicate does actually address your question, but you need to adjust it to your situation and not just copy paste.

DataA.options = DataA.options.map((item, i) => Object.assign({}, item, DataB.options[i]));

but since this mutates the original DataA object anyway, you may as well just use forEach() and avoid creating the intermediate array from .map().

DataA.options.forEach((item, i) => Object.assign(item, DataB.options[i]));

Both of the above assume that the options arrays of both objects are a. of the same length, and b. sorted by id. To avoid these assumptions you can use .find() to look for matching elements instead of relying on index.

DataA.options.forEach(item =>
  Object.assign(item, DataB.options.find(({ id }) => id === item.id)));

const DataA = {
  "id": 57,
  "status": true,
  "options": [
    { "id": 1, "name": "Type A" },
    { "id": 2, "name": "Type B" },
    { "id": 3, "name": "Type C" }]
}

const DataB = {
  "id": 57,
  "status": true,
  "options": [
    { "id": 1, "value": 10 },
    { "id": 2, "value": 20 },
    { "id": 3, "value": 30 }]
}

DataA.options.forEach(item =>
  Object.assign(item, DataB.options.find(({ id }) => id === item.id)));

console.log(DataA)
.as-console-wrapper { max-height: 100% !important; top: 0; }
pilchard
  • 12,414
  • 5
  • 11
  • 23