[英]Modify array of objects into new array of objects in JavaScript
我想如何將 object 轉換為 JavaScript 中的對象數組。 在 object obj
中,字段應修改為 JavaScript 中的嵌套對象數組。
var obj = [{ id: 1, fields: { color: "white", brand: "xyz" } }] function objarray(obj) { return obj.map(e => ({ label: Object.keys(e.fields) })) } var result = objarray(obj); console.log(result);
預期 Output:
[
{
label: "color",
children: [{label:"white" }]
},
{
label: "brand",
children: [{label:"xyz" }]
}
]
Obj.map 不起作用,因為 obj 是一個只有一個元素的數組,所以它只會迭代一次。
let newArray = []
for (var i in obj.fields)
{
newArray.push({label: i, children:obj[[0].fields.i});
}
我懷疑這會編譯。 我懷疑我在這里是 object,不能用作 obj[0].fields 的參考。
但你明白了。
這應該可以解決問題
var obj = [{
id: 1,
fields: {
color: "white",
brand: "xyz"
}
}]
const mapFields = (obj) => {
return obj.map((o) => {
return Object.keys(o.fields).map((f) => {
var field = {
label: f,
children: [{label: o.fields[f]}]
};
return field;
});
})
}
console.log(mapFields(obj));
您可以通過使用Object.entries()
來做到這一點:
var obj = [ { id: 1, fields: { color: "white", brand: "xyz" } }]; result = Object.entries(obj[0].fields).map(([k,v])=>({label:k, children:[{label:v}]})) console.log(result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.