[英]How to change the nested array object to object depending on type in javascript
我想知道如何根據 javascript 中的鍵將嵌套數組 object 更改為 object
我有對象obj1
和obj2
,根據關鍵item
類型更改 object。
function changeObj(obj){
let result = obj.reduce(function (acc, item) {
if(item.items.trim() !== "" && item.key.trim() !== ""){
acc[item.key] = item.items
return acc
}
return acc
}, {});
return result;
}
let result = this.changeObj(obj2)
var obj1 = [
{ id:0, items:["SG","AU"], count: 2, key:"countries"},
{ id:1, items:["finance"], count: 3 key:"info"}
]
var obj2 = [
{ id:0, items: "SG", key: "country"},
{ id:1, items: "details", key: "info"}
]
Expected Output:
// if items key is array
{
fields: {
countries: ["SG","AU",2],
info: ["finance",3]
}
}
//if items key is string
{
fields: {
country: "SG",
info: "details"
}
}
我認為您的代碼未運行的原因是您的對象(1 和 2)格式錯誤。 除了條件之外,您的代碼還可以,因為trim()
僅適用於字符串類型,因此它在數組上出錯。 試試這個代碼片段
function changeObj(obj){ let result = obj.reduce(function (acc, item) { acc[item.key] = item.items; return acc; }, {}); return result; } var obj1 = [ { id:0, items:["SG","AU"], count: 2, key:"countries"}, { id:1, items:["finance"], count: 3, key:"info"} ] var obj2 = [ { id:0, items: "SG", key: "country"}, { id:1, items: "details", key: "info"} ] console.log(changeObj(obj1));
const changeObj = obj => obj.reduce((acc, item) => { if (Array.isArray(item.items)) { acc[item.key] = [...item.items, item.count]; } else { acc[item.key] = item.items; } return acc; }, {}); var obj1 = [ { id: 0, items: ['SG', 'AU'], count: 2, key: 'countries' }, { id: 1, items: ['finance'], count: 3, key: 'info' } ]; var obj2 = [ { id: 0, items: 'SG', key: 'country' }, { id: 1, items: 'details', key: 'info' } ]; console.log(changeObj(obj1)); console.log(changeObj(obj2));
或者清理得更多
const changeObj = obj => obj.reduce((acc, { items, key, count }) => { Array.isArray(items)? (acc[key] = [...items, count]): (acc[key] = items); return acc; }, {}); var obj1 = [ { id: 0, items: ['SG', 'AU'], count: 2, key: 'countries' }, { id: 1, items: ['finance'], count: 3, key: 'info' } ]; var obj2 = [ { id: 0, items: 'SG', key: 'country' }, { id: 1, items: 'details', key: 'info' } ]; console.log(changeObj(obj1)); console.log(changeObj(obj2));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.