从对象获取值并推入数组javascript

时间:2018-10-27 01:36:04

标签: javascript arrays json object ecmascript-6

我想从对象中获取值并将其保存到数组中...这就是我的对象的结构。

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

但是我正在寻找类似的东西。

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

这是我被困住的地方。

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

3 个答案:

答案 0 :(得分:3)

您可以使用函数Array.prototype.map遍历数据,并在每个对象上运行函数Object.values以将其值提取为数组。

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

请注意,以这种方式遍历对象的属性可能会在arbitrary order中返回,因此,如果需要确保顺序,则应使用自定义函数来提取值(使用ES6解构尤其容易) :

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

答案 1 :(得分:0)

尝试一下:

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

答案 2 :(得分:0)

另一种选择是使用Object.values()方法。

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

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