Gitesh Purbia
Gitesh Purbia

Reputation: 1104

Javascript Move all array Elements inside Object of Objects

Is there any short way to move all array elements inside object of objects. For Ex- I have an array like

var a =  [
   {
     'a': 'a',
     'test' : 'test'
   },
   {
      'b' : 'b',
      'test' : 'test'
   }
]

I want to move this array elements inside object so it looks like:

var a = {
"test" : {
    0: {
        'a' : 'a',
       'test' : 'test'
    },
    1: {
        'b' : 'b',
        'test' : 'test'
    }
}

};

"test" inside a should not be an array, as i am creating XML with this data. How can i accomplish with javascript ?

Upvotes: 1

Views: 412

Answers (3)

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48751

You can reduce the array into an object wrapped with a root property.

var a = [{
  'a': 'a',
  'test': 'test'
}, {
  'b': 'b',
  'test': 'test'
}];

console.log(wrap(a, 'test'));

function wrap(arr, root) {
  return {
    [root]: arr.reduce((obj, item, index) => {
      return Object.assign(obj, { [index]: item })
    }, {})
  }
}
.as-console-wrapper { top: 0; max-height: 100% !important; }

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386883

You could assign the array to an object. This keeps the indices as keys and returns an object.

var a =  [{ a: 'a', test: 'test' }, { b: 'b', test: 'test' }],
    result = { test: Object.assign({}, a) };

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 5

jo_va
jo_va

Reputation: 13993

You can use reduce:

const a =  [
  { 'a': 'a', 'test' : 'test' },
  { 'b' : 'b', 'test' : 'test' }
];

const output = {
  test: a.reduce((acc, x, i) => {
    acc[i] = x;
    return acc;
  }, {})
};

console.log(output);

Upvotes: 1

Related Questions