Home > Back-end >  How can I merge two arrays with the type and key value in ES6
How can I merge two arrays with the type and key value in ES6

Time:09-22

I have two arrays like below:

const array1 = [
  { type: 'BA', value: 100 },
  { type: 'CA', value: 200 },
];
const array2 = [
  {
    NameBA: 'STANDARD',
    NameDescriptionBA: 'STANDARD',
    AgeBA: 0,
    NameCA: 'STANDARD',
    NameDescriptionCA: 'STANDARD',
    AgeCA: 0,
  },
]

The array1 has the type value 'BA', I have to find the array2 keys last 2 characters includes with the array1 type value 'BA' and merge to the related object of array1.

My expected result is

cosnt array1 = [
  { 
    type: 'BA', 
    value: 100,
    NameBA: 'STANDARD',
    NameDescriptionBA: 'STANDARD',
    AgeBA: 0,
  },
  { 
    type: 'CA',
    value: 200,
    NameCA: 'STANDARD',
    NameDescriptionCA: 'STANDARD',
    AgeCA: 0,
  },
]

I tried the below method but the output is incorrect

const keys = Object.keys(array2[0]);
array1.map(a => {
  keys.map(b => {
    if (b.includes(a.type)) {
      array2.map(c => {
        a.b = c.b
      })
    }
  });
});

CodePudding user response:

You're only using one object from the second array, so just changing that definition to be an object instead, you can convert the object to key/value pairs, and filter() them down to match the type:

const array = [
  { type: 'BA', value: 100 },
  { type: 'CA', value: 200 },
];

const object = {
  NameBA: 'STANDARD',
  NameDescriptionBA: 'STANDARD',
  AgeBA: 0,
  NameCA: 'STANDARD',
  NameDescriptionCA: 'STANDARD',
  AgeCA: 0,
};

const result = array.map(({type, value}) => ({
  type,
  value,
  ...Object.fromEntries(
    Object.entries(object).filter(([k, v]) => k.endsWith(type))
  )
}));

console.log(result);


If your second array is indeed an array with multiple objects, just throw in a flatMap() to flatten all the object entries:

const array1 = [
  { type: 'BA', value: 100 },
  { type: 'CA', value: 200 },
];

const array2 = [{
  NameBA: 'STANDARD',
  NameDescriptionBA: 'STANDARD',
  AgeBA: 0,
  NameCA: 'STANDARD',
  NameDescriptionCA: 'STANDARD',
  AgeCA: 0,
}];

const result = array1.map(({type, value}) => ({
  type,
  value,
  ...Object.fromEntries(
    array2.flatMap(Object.entries).filter(([k, v]) => k.endsWith(type))
  )
}));

console.log(result);

CodePudding user response:

You can do something like this.

const array1 = [
  { type: 'BA', value: 100 },
  { type: 'CA', value: 200 },
];
const array2 = [
  {
    NameBA: 'STANDARD',
    NameDescriptionBA: 'STANDARD',
    AgeBA: 0,
    NameCA: 'STANDARD',
    NameDescriptionCA: 'STANDARD',
    AgeCA: 0,
  },
]

const keys = Object.keys(array2[0]);
const result = array1.map(a => {
  let currentObject = {}
  keys.map(b => {
    if (b.indexOf(a.type) !== -1) {
      currentObject = {
         ...currentObject,
         ...a, 
         [b]: array2[0][b]
      }
    }
  });
  return currentObject;
});

console.log(result)

  • Related