简体   繁体   中英

get values from object and push into array javascript

I would like to get values from object and save it into array...This is how my object is structured.

0: {name: "John Deo", age: 45, gender: "male"}
1: {name: "Mary Jeo", age: 54, gender: "female"}
2: {name: "Saly Meo", age: 55, gender: "female"}

But I am looking for something like this.

0: ["John Deo", 45, "male"]
1: ["Mary Jeo", 54, "female"]
2: ["Saly Meo", 55, "female"]

This is where I got stuck.

for(let i in data){
   _.map(data[i], value =>{
        console.log(value)
    })
}

You can use the function Array.prototype.map to iterate over your data and run the function Object.values on each object to extract its values as an array.

 const data = [ {name: "John Deo", age: 45, gender: "male"}, {name: "Mary Jeo", age: 54, gender: "female"}, {name: "Saly Meo", age: 55, gender: "female"} ]; result = data.map(Object.values); console.log(result); 

Note that iterating over properties of an object this way might return then in an arbitrary order so if you need to ensure the order you should use a custom function to extract the values (this is especially easy using ES6 destructuring):

 const data = [ {name: "John Deo", age: 45, gender: "male"}, {name: "Mary Jeo", age: 54, gender: "female"}, {name: "Saly Meo", age: 55, gender: "female"} ]; const extractValues = ({name, age, gender}) => [name, age, gender]; result = data.map(extractValues); console.log(result); 

尝试这个:

data.map(obj => Object.values(obj))

Another option would be to use the Object.values() method.

var obj = {name: "John Deo", age: 45, gender: "male"}; 

console.log(Object.values(obj));

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