4

Hello I have object like this:

var obj = { banana: 1425, orange: 1683}

and I need array of objects created on the basis of items. for example:

[{name: banana, value: 1425}, {name: orange, value: 1683}]

I did it in this way :

var fruits = [];
_.each(obj, function(value, name){
    fruits.push({
        name: name,
        value: value
    });
});

maybe you know an easier way?

1

2 Answers 2

10

You can use underscore's _.map on an object :

var obj = { banana: 1425, orange: 1683};

var fruits = _.map(obj, function(value, key){
  return { name : key, value : value };
});

http://underscorejs.org/#map

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

Comments

0

You could also just use Object.entries()

let myobj = {banana: 1425, orange: 1683};
let entries = Object.entries(myobj); // => [['banana', 1425], ['orange', 1683]];


//and if you want it in array-object format:
let other_format = Object.entries(myobj).map(entry => {
    return {[entry[0]]: entry[1]}
}); // => [{banana: 1425}, {orange: 1683}]

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.