0

I have an array which contain multiple objects, like

var val = [
    _id: ["5412fc1bd123cf7016674a92", "5412cf270e9ca9b517b43ca3"],
    _id: ["5412cf5a6cc4f4bc151fd220"]
];

I want to change to single array, like:

var val = [
    "5412fc1bd123cf7016674a92", 
    "5412cf270e9ca9b517b43ca3", 
    "5412cf5a6cc4f4bc151fd220"
];

I'm using _.pluck() but its not giving me the output which I want. How can I achieve this?

4
  • Are you sure about your example code? Shouldn't it be an object containing multiple arrays instead? Commented Sep 15, 2014 at 7:16
  • yes i'm sure about my code. Commented Sep 15, 2014 at 7:19
  • 1
    Then it's not valid JavaScript. Commented Sep 15, 2014 at 7:21
  • I'm getting ids from arrays of objects and put all in single variable called 'val'. Commented Sep 15, 2014 at 7:21

2 Answers 2

5

Update: This is 2019 and Array.flat is native.

const val = {
  _id: ["5412fc1bd123cf7016674a92", "5412cf270e9ca9b517b43ca3"],
  _id2: ["5412cf5a6cc4f4bc151fd220"]
}

console.log(
  Object.values(val).flat()
)

// Without flat
console.log(
  Array.prototype.concat.apply(
    [],
    Object.values(val)
  )
)

// Without Object.values
console.log(
  Array.prototype.concat.apply(
    [],
    Object.keys(val).map(k => val[k])
  )
)

The following is all you need with lodash:

_.flatten(_.values(val))
Sign up to request clarification or add additional context in comments.

Comments

1

Assuming your input data is an object containing several arrays, like so:

var val = {
    _id: ["5412fc1bd123cf7016674a92", "5412cf270e9ca9b517b43ca3"],
    _id2: ["5412cf5a6cc4f4bc151fd220"]
};

You can get the desired array structure pretty easily using concat:

var flat = [];
for (var key in val) {
    flat = flat.concat(val[key]);
}
console.log(flat);

Output:

[ '5412fc1bd123cf7016674a92',
  '5412cf270e9ca9b517b43ca3',
  '5412cf5a6cc4f4bc151fd220' ]

2 Comments

That wouldn't make any sense, because keys must be unique. OP probably has a collection (array of objects)
Oops, copy-pasted the duplicate key.

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.