我有以下对象:
let categories = {
"Asset Type": ["appliances", "electronics"],
"Asset Availability": ["in stock"]
}
我需要将其转换为以下结构:
[
{
"name": "Asset Type",
"values": ["Appliances", "Electronics"]
},
{
"name": "Asset Availability",
"values": ["In Stock"]
}
]
答案 0 :(得分:7)
使用Object.entries
,array.prototype.map
和一些destructuring
:
var categories = {
"Asset Type": ["appliances", "electronics"],
"Asset Availability": ["in stock"]
};
var res = Object.entries(categories).map(([name, values]) => ({name, values}));
console.log(res);

答案 1 :(得分:2)
const categories = {
"Asset Type": ["appliances", "electronics"],
"Asset Availability": ["in stock"]
}
const toArray = obj =>
Object.keys(obj).reduce((acc, key) => [...acc, {name: key, values: obj[key]}], [])
console.log(toArray(categories));

答案 2 :(得分:2)
我最喜欢的方法是:
请注意,此方法中的密钥必须是唯一的(无论如何都应该如此):
var categories = {
"Asset Type": ["appliances", "electronics"],
"Asset Availability": ["in stock"]
};
var res = Object.keys(categories).map(key => ({
name: key,
values: categories[key]
});
);
console.log(res);
答案 3 :(得分:0)
尝试这样==>
var obj = {
"categories":
{
"Asset Type": ["appliances", "electronics"],
"Asset Availability": ["in stock"]
},
};
var categories = [];
for(let p in obj.categories) {
categories.push({
name: p,
values : obj.categories[p]
});
}
console.log(categories);
答案 4 :(得分:0)
你可以尝试这样的东西或使用地图功能有很多方法
let obj = {
"categories":
{
"Asset Type": ["appliances", "electronics"],
"Asset Availability": ["in stock"]
}
}
let categories=[];
Object.keys(obj.categories).forEach(key=>{
categories.push({"name":key,"value":obj.categories[key]});
});
console.log(categories);