1

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 ?

1
  • Something like this? arr.reduce((result,item,index)=>{result[index]=item;return result;},{}) Commented Feb 11, 2019 at 14:29

3 Answers 3

5

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; }

Sign up to request clarification or add additional context in comments.

1 Comment

That's a nice way to do it! +1
1

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);

Comments

1

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; }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.