Home > OS >  Combining two arrays in an object but keep the key
Combining two arrays in an object but keep the key

Time:08-24

I need to combine two arrays in an object.

const mainObject = {
    user: [{
        a: "aaaa",
        b: "bbbb"
    }, {
        c: "cccc",
        d: "dddd"
    }],
    developer: [{
        e: "eeee",
        f: "ffff"
    }]
}

I can combine them easily using mainObject.user.concat(mainObject.developer). But the resulting object loses the origin:

[{
    a: "aaaa",
    b: "bbbb"
}, {
    c: "cccc",
    d: "dddd"
},{
    e: "eeee",
    f: "ffff"
}]

The output I need is:

[{
    a: "aaaa",
    b: "bbbb",
    origin: "user"
}, {
    c: "cccc",
    d: "dddd",
    origin: "user"
},{
    e: "eeee",
    f: "ffff",
    origin: "developer"
}]

CodePudding user response:

There are multiple ways to do this, one way would be to use a map and concat

const mainObject = {
  user: [{
    a: "aaaa",
    b: "bbbb"
  }, {
    c: "cccc",
    d: "dddd"
  }],
  developer: [{
    e: "eeee",
    f: "ffff"
  }]
}

const result = mainObject.user.map(item => ({ ...item,
  origin: 'user'
})).concat(mainObject.developer.map(item => ({ ...item,
  origin: 'developer'
})));

console.log(result);

or another method

const mainObject = {
  user: [{
    a: "aaaa",
    b: "bbbb"
  }, {
    c: "cccc",
    d: "dddd"
  }],
  developer: [{
    e: "eeee",
    f: "ffff"
  }]
}

const result = Object.entries(mainObject).map(([key, value]) => {
  return value.map(item => ({ ...item,
    origin: key
  }))
}).flat();

console.log(result);

CodePudding user response:

You can use reduce and forEach to iterate the data and add the origin property

const mainObject = {
  user: [{
    a: "aaaa",
    b: "bbbb"
  }, {
    c: "cccc",
    d: "dddd"
  }],
  developer: [{
    e: "eeee",
    f: "ffff"
  }]
}

const result = Object.entries(mainObject)
  .reduce((acc, [origin, value]) => {
    value.forEach(value2 => {
      acc.push({ ...value2,
        origin
      })
    })

    return acc
  }, [])

console.log(result)

  • Related