0

I have an array with objects returned by a server like this:

myArr = [{
    "id": 1
}, {
    "id": 2
}, {
    "id": 3
}, {
    "id": 4
}, {
    "id": 5
}, {
     "id": 6
}, {
    "id": 7
}, {
    "id": 8
}, {
    "id": 9
}, {
    "id": 10
}];

I need this to become:

myArr = [
    1, 2, 3, 4, 5, 6, 7, 8, 9, 10
];

I can loop through the array of course, something like:

// array to hold property values
let myNewArr = [];

// loop through the objects and take the value of id of each object
for (let i = 0; i < myArr.length; ++i) {
    myNewArr.push(myArr[i].id);
}

Is there a more efficient way to do this, preferably using Lodash? I don't want to add another loop to the code, as it's already riddled with loops.

2 Answers 2

4

Array map is what you're looking for:

myArr.map(function(x){ return x.id; })

It automatically cycles your array and "extract" the id value of your inner objects, returning an array.

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

1 Comment

Thanks! I accepted Hussain's answer, though, because he used Lodash (it allows my code to be more similar to the rest of the code I'm working on).
1

with lodash:

let myArr = _.map(myArr, (b) => b.id);

with arrow operator:

let d = myArr.map(b => b.id);

1 Comment

Thanks this is perfect :)

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.