本文介绍了从对象获取值并推入数组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)
    })
}

推荐答案

您可以使用Array.prototype.map 迭代您的数据并运行函数 Object.values 在每个对象上提取其值作为数组.

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

请注意,以这种方式迭代对象的属性可能会在 任意顺序 所以如果你需要确保顺序,你应该使用自定义函数来提取值(使用 ES6 解构尤其容易):

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

这篇关于从对象获取值并推入数组javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 14:27
查看更多