Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
387 views
in Technique[技术] by (71.8m points)

javascript - Push only values of an object array into another array

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...