[英]How to change the nested array object to object depending on type in javascript
I would like to know how to change nested array object to object depending on key in javascript我想知道如何根据 javascript 中的键将嵌套数组 object 更改为 object
I have objects obj1
and obj2
, depending on key item
type change the 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"
}
}
I think the reason your code is not running is because the wrong format of your objects (1 and 2).我认为您的代码未运行的原因是您的对象(1 和 2)格式错误。 Your code is okay except the condition because trim()
only works on string type so it errors on array.除了条件之外,您的代码还可以,因为trim()
仅适用于字符串类型,因此它在数组上出错。 Try this code snippet试试这个代码片段
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));
or cleaned up even more或者清理得更多
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.