简体   繁体   中英

Push all values from object to array?

I'm just starting as a programmer. Can someone help me with this problem? All I have so far is:

var myArr = [];
for (var k in input) {
    myArr.push(

Am I on the right track?

Write a loop that pushes all the values in an object to an array.

input: {two: 2, four: 4, three: 3, twelve: 12}
output: [2, 4, 3, 12]

Without loop:

const input = {two: 2, four: 4, three: 3, twelve: 12};
const myArr = Object.values(input);
console.log(myArr);
// output: [2, 4, 3, 12]

If you writing it in javascript native, use the push() function:

for example:

var persons = {roy: 30, rory:40, max:50};

var array = [];

// push all person values into array
for (var element in persons) {
    array.push(persons[element]);
}

good luck

input = {two: 2, four: 4, three: 3, twelve: 12}

const output = Object.keys(input).map(i => input[i])

[2, 4, 3, 12]

This will help you to find exact output.

This link will provide you more information https://medium.com/chrisburgin/javascript-converting-an-object-to-an-array-94b030a1604c

 var myArr = []; var input = {two: 2, four: 4, three: 3, twelve: 12}; for (var k in input) { myArr.push(input[k]); } alert(myArr);

data.input[k] is what you want

var data = {input: {two: 2, four: 4, three: 3, twelve: 12}}, myArr = [];

for(k in data.input) myArr.push(data.input[k]);

Using underscore.js :

var myArr = _.values(input);

It's a very useful library, and only 5.3k when gzipped

In each iteration of the for in loop the variable k gets assigned the next property name in the object input , so you have to push input[k] . For the case that the object has properties from its prototype and you only want to push the objects own properties to the array (that is probably what you want to do) you should use hasOwnProperty .

var input: {two: 2, four: 4, three: 3, twelve: 12}
var myArr = [];
for (var k in input) {
//  if( input.hasOwnProperty( k) ) { //not necessary
    myArr.push( input[k] );
//  } 
}

Be aware that for in loops over the object in arbitrary order, ie, the order of the items in the array might not be what you expect it to be.

See also: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

EDIT: as Alnitak has mentioned in a comment to the OP it is probably not necessary to use hasOwnPropery() nowadays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM