如何解决如何根据JavaScript中的类型将嵌套数组对象更改为对象
我想知道如何根据javascript中的键将嵌套数组对象更改为对象
我有对象obj1
和obj2
,具体取决于键item
的类型来更改对象。
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"},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"},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'],key: 'countries' },{ id: 1,items: ['finance'],key: 'info' }
];
var obj2 = [
{ id: 0,items: 'SG',key: 'country' },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;
},key: 'info' }
];
console.log(changeObj(obj1));
console.log(changeObj(obj2));
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。