0

i used to have an array with one object, like so: var myObj = [{'key': {an object}}];

I convert it to an object like so: Object.assign({}, ...myobj)

to get this : {'key': [{an object}]}

The issue, is that on myobj now i have two items, with the same KEY, like so:

[{'key': {an object}}, {'key': {another object}}]

The result that i get if i execute the same Object.assign is one object with two other objects inside it, and it normal: {'key': {an object}}, {'key': {another object}}

The question is can i convert my myobj to an that structure:

{'key': [{an object}, {another object}]}
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Theo Itzaris
  • 4,321
  • 3
  • 37
  • 68
  • You can certainly write code to do that. But not nicely and automatically with `Object.assign`. – Amadan Sep 26 '18 at 10:51
  • `let newObj = { key: myObj.map(o => Object.assign({}, o.key)) };` – ibrahim mahrir Sep 26 '18 at 10:58
  • "*The result that i get if i execute the same Object.assign is one object with two other objects inside it,*". Actually no, you get a object with a single key contain the last object that shared that key, so `{'key': {another object}}` – Gabriele Petrioli Sep 26 '18 at 10:59
  • rather I will suggest you to use lodash, you can just do `_.groupBy(_.flatMap(arr, _.entries), 0)`. let me know if you need a detail answer on lodash explaining this – Koushik Chatterjee Sep 26 '18 at 11:14

5 Answers5

0

You can use Array.map():

const data = [{'key': 'an object'}, {'key': 'another object'}];

const result = {
  key: data.map(o => o.key)
};

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

You can manually merge objects by looping over their entries and replacing the values by arrays. Here's an example of a merge function that you can use with two arguments, or in a reduce:

const mergeObjects = (obj1, obj2) => 
  [...Object.entries(obj1), ...Object.entries(obj2)].reduce(
    (merged, [k, v]) => Object.assign(
      merged,
      { [k]: (merged[k] || []).concat(v) }
    ),
    {}
  );

console.log(mergeObjects({ key: "a"}, { key: "b" }));
console.log(
  [
    { key: "a", test: "b" }, { key: "c" }, { key: "d" } 
  ].reduce(mergeObjects)
);
user3297291
  • 22,592
  • 4
  • 29
  • 45
0

You could merge the object by using the same key for the first level.

function merge(...objects) {
    return objects.reduce((a, b) => {
        Object.entries(b).forEach(([k, v]) => {
            if (!(k in a)) {
                return a[k] = v;
            }
            if (!Array.isArray(a[k])) {
                a[k] = [a[k]];
            }
            a[k].push(v);
        });
        return a;
    }, {});
}
    
console.log(merge({ key: { foo: 'bar' } }, { key: { foo: 'baz' } }));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0
const finalObj = {};
const myObj =  [{'key': { obj : "hello"}}, {'key': { obj : "hello"}}, {'key2': {obj : "world"}}, {'key3': {obj : "world"}}];

for( const oj of myObj) {
  const key = Object.keys(oj)[0];

  if(finalObj[key]){
     const tempArray =[].concat(finalObj[key]);
     tempArray.push(oj[key]);
     finalObj[key] = tempArray         
  }else{
   finalObj[key] = oj[key];
  }

}

console.log(finalObj);

Final Output : {"key":[{"obj":"hello"},{"obj":"hello"}],"key2":{"obj":"world"},"key3":{"obj":"world"}}
0

You can use reduce to achieve this

        const obj = [{key: {val: 1}}, {key: {val: 2}}]
        const reqObj = obj.reduce((acc, cur) => [...acc, cur.key],[])
        console.log('reqObj: ', reqObj)
Vijay
  • 169
  • 7