0

Trying to transform an object of objects:

var items: {
    item_a: {
        state: 'item_a status'
    },
    item_b: {
        state: 'item_b status'
    }
};

into an array of objects, whilst adding a new array element to the object (the object key):

var items = [{
    name: 'item_a',
    state: 'item_a status'
}, {
    name: 'item_b',
    state: 'item_b status'
}];

My naive attempt, which works, is thus:

var arrayOfItems = [];
for(var x in items){
    var itemObj = {
        name: x
    };
    for(var y in items[x]){
        itemObj[y] = items[x][y];
    }
    arrayOfItems.push(itemObj);
}

I'm wondering if there's a cleaner way to do this, using maybe something Underscore/LoDash?

1
  • When you are posting a question, please include all the requirements in the question. Commented May 14, 2015 at 14:48

2 Answers 2

1

I would use map() for this:

_.map(items, function(item, key) {
    return _.assign({ name: key }, item);
});
// →
// [
//   {
//     name: 'item_a',
//     state: 'item_a status'
//   },
//   {
//     name: 'item_b',
//     state: 'item_b status'
//   }
// ]

Since map() always returns an array, you're halfway there. You just need the callback to generate your array items. You can use the assign() function to setup your new name property, and then add the rest of the properties.

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

Comments

0
var newItems = _.map(items, function(item, key){
  item.name = key;
  return item;
});
console.log(newItems);

1 Comment

This mutates the original object. I feel that, this beats the important idea in functional programming, not mutating objects.

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.