2

I have the following array;

["Test1", "Test2", "Test3"]

I want it to be like this;

[{ id: 0, name: "Test1" }, { id: 1, name: "Test2" }, { id: 2, name: "Test3" }]

Any Help? I guess I should somehow use _.object() for this mission.

3 Answers 3

7

The map() function is your friend:

_.map(array, function(item, index) {
    return { id: index, name: item };
});
Sign up to request clarification or add additional context in comments.

Comments

1

As you are using angular this should simply do the trick.

var newArray = [];
angular.forEach(myArray,function(item, key){
    newArray.push({id:key, name:item});
});

Comments

1

The following solution does not require angular and is just based on lodash:

var newArray = [];

_.forEach(["Test1", "Test2", "Test3"], function (item, key) {
    newArray.push({
        id: key,
        name: item
    });
});

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.