如何在Javascript中将对象数组的对象转换为对象数组

时间:2018-04-26 06:19:43

标签: javascript arrays object

我有对象数组的对象

{
  "94":[{"Full Name":"Phalla Morn"}],
  "95":[{"Full Name":"Pum Chhenghorng"}],
  "99":[{"Full Name":"Proen Pich"}]
}

我想将其转换为对象数组

[
  {"Full Name":"Phalla Morn"}, 
  {"Full Name":"Pum Chhenghorng"},
  {"Full Name":"Proen Pich"}
]

请帮忙。

6 个答案:

答案 0 :(得分:6)

使用Object.values()获取内部数组,并将spreading展平为Array.concat()



const arr = {"94":[{"Full Name":"Phalla Morn"}],"95":[{"Full Name":"Pum Chhenghorng"}],"99":[{"Full Name":"Proen Pich"}]};
    
const result = [].concat(...Object.values(arr));

console.log(result);




答案 1 :(得分:2)

使用Object.values从对象中提取值,然后使用[].concat(...进行flatmap:

const input = {
  "94": [{
    "Full Name": "Phalla Morn"
  }],
  "95": [{
    "Full Name": "Pum Chhenghorng"
  }, {
    "Full Name": "example other"
  }],
  "99": [{
    "Full Name": "Proen Pich"
  }]
};
const output = [].concat(...Object.values(input));
console.log(output);

答案 2 :(得分:2)

您可以尝试以下操作:



var obj = {
    "94":[{"Full Name":"Phalla Morn"}],
    "95":[{"Full Name":"Pum Chhenghorng"}],
    "99":[{"Full Name":"Proen Pich"}]
    }

var arr = Object.values(obj).map(o => o[0]);
console.log(arr)




答案 3 :(得分:0)

您可以使用两个forEach循环,并确保如果数组9495中有多个对象,则此动态代码逻辑也会考虑这一点:

let obj = {
  "94":[{"Full Name":"Phalla Morn"}],
  "95":[{"Full Name":"Pum Chhenghorng"}],
  "99":[{"Full Name":"Proen Pich"}]
}; 
let res = [];
Object.keys(obj).forEach((key)=>{
   obj[key].forEach((innerObj)=>{
     res.push(innerObj);
   }); 
});
console.log(res);

或者您可以将Object.valuesspread运算符一起使用:

let obj = {
  "94":[{"Full Name":"Phalla Morn"}],
  "95":[{"Full Name":"Pum Chhenghorng"}],
  "99":[{"Full Name":"Proen Pich"}]
}; 
let res = [];
Object.keys(obj).forEach((key)=>{
    res.push(...Object.values(obj[key]));
});
console.log(res);

答案 4 :(得分:0)

Plain JS - 因为IE根本不支持Object.values

var arr = [],
    obj =  {"94":[{"Full Name":"Phalla Morn"}],"95":[{"Full Name":"Pum Chhenghorng"}],"99":[{"Full Name":"Proen Pich"}]};

Object.keys(obj).forEach(function(k) {
  arr.push(obj[k][0])
});
console.log(arr)

答案 5 :(得分:0)

试试这个:它应该处理其值中有多个对象的数组。

let data = {
      "94": [{
        "Full Name": "Phalla Morn"
      }],
      "95": [{
        "Full Name": "Pum Chhenghorng"
      },{
        "Full Name": "Ryann"
      }],
      "99": [{
        "Full Name": "Proen Pich"
      }]
    };
    
    let obj = [];
    
    Object.keys(data).map(item => {
      data[item].map(item => {
        obj.push(item);
      });
    });
    
    console.log(obj);