-2

I am looking to push only the values of ObjArray into another array called Array.

var Array = [];

var ObjArray = [{item1 : 'Foo'}, {item2 : 'Bar'}];

// Push Values from ObjArray into Array

pushValues(ObjArray, Array);

The expected output would be Array having only ['Foo', 'Bar']

Thanks!

edit: Sorry. I am asking how to push all values from ObjArray into Array.

2
  • What makes your keys as item1, item2.. ? Commented Jul 27, 2019 at 4:16
  • @CuongLeNgoc - Names of keys are not identical to use Arraay#map Commented Jul 27, 2019 at 4:16

2 Answers 2

0

You can try with Array.prototype.map()

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

And Object.values()

The Object.values() method returns an array of a given object's own enumerable property values.

As you have single value in the object use [0] to return that.

var ObjArray = [{item1 : 'Foo'}, {item2 : 'Bar'}];
var array = ObjArray.map(i => Object.values(i)[0]);
console.log(array);

Using for...of and push()

var array = [];
var ObjArray = [{item1 : 'Foo'}, {item2 : 'Bar'}];
for(var i of ObjArray){
  array.push(Object.values(i)[0]);
}
console.log(array);

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

Comments

0

If your objects have multiple key-value pairs within them you can use a combination of .flatMap() with Object.values() like so:

const objArray = [{a: 'foo', b: 'bar'}, {c : 'baz'}];
const arr = objArray.flatMap(Object.values);

console.log(arr); // ["foo", "bar", "baz"]

However, do note, .flatMap() does have limited browser support, and so, if you need something a little more compatible, you can use .reduce() instead:

const objArray = [{a: 'foo', b: 'bar'}, {c : 'baz'}];
const arr = objArray.reduce((a, o) => [...a, ...Object.values(o)], []);

console.log(arr); // ["foo", "bar", "baz"]

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.