0

Imagine I have

const obj = {
  arr_a: [9, 3, 2],
  arr_b: [1, 5, 0],
  arr_c: [7, 18]
}

what's the best way to convert this object to a simple array like:

[9, 3, 2, 1, 5, 0, 7, 18]

I tried this:

[].concat(obj.arr_a, obj.arr_b, obj.arr_c)

But I wonder if there's something in lodash or underscore to do it. Something like:

_.flatAsArray(obj);

or:

obj.toFlatArray();
3
  • Is it just arr_a,b,c or n properties you are looking for ? Commented Apr 13, 2017 at 11:48
  • Are there always 3 known properties? Commented Apr 13, 2017 at 11:48
  • In this case yes but I'd prefer to know a more dynamic way Commented Apr 13, 2017 at 11:48

5 Answers 5

1

To get the values of all keys in object, you can use _.values.

With ES6

[].concat(..._.values(obj))

With _.flatten

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

Comments

1

You can use flatMap to get all these values.

var result = _.flatMap(obj);

const obj = {
  arr_a: [9, 3, 2],
  arr_b: [1, 5, 0],
  arr_c: [7, 18]
};

var result = _.flatMap(obj);

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>

Comments

0

What about:

_.flatten(_.values(obj));

Comments

0

You could use Object.values and Array#reduce.

var obj = { arr_a: [9, 3, 2], arr_b: [1, 5, 0], arr_c: [7, 18] },
    result = Object.values(obj).reduce((r, a) => r.concat(a));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

You can use Object.values to iterate over the object values, reducing them using the spread operator

Object.values(obj).reduce((result, val) => [...result, ...val], [])

2 Comments

While this code snippet may be the solution, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
@Adam thanks for the feedback, I've edited my answer

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.