Rajeev
Rajeev

Reputation: 1113

convert multiple arrays objects to single array, underscore

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?

Upvotes: 0

Views: 1554

Answers (2)

kornieff
kornieff

Reputation: 2557

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))

Upvotes: 5

Jean-Karim Bockstael
Jean-Karim Bockstael

Reputation: 1405

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' ]

Upvotes: 1

Related Questions