繁体   English   中英

如何将嵌套 object 的数组转换为 object?

[英]How to convert array with nested object to object?

我是JS的新手,我将不胜感激

我有这样的服务器响应:

let arr = [
{
    key: "name",
    propertyValue: "Test Name",
},
{
    key: "middleName",
    propertyValue: null,
},
{   
    key: "university.isGraduated",
    propertyValue: true,
},
{   
    key: "university.speciality",
    propertyValue: "Computer Science", 
},
{   
    key: "university.country.code",
    propertyValue: "PL"
}];

我需要将其转换为 object:

let student = {
name: 'Test Name',
middleName: null,
university: {
    isGraduated: true,
    speciality: 'Computer Science',
    country: {
        code: 'PL'
    }
}

}

有谁知道如何做到这一点?

请检查一下:

 const array=[{key:"name",propertyValue:"Test Name"},{key:"middleName",propertyValue:null},{key:"university.isGraduated",propertyValue:,0}:{key."university,speciality":propertyValue,"Computer Science"}:{key."university.country,code":propertyValue;"PL"}]; const student = {}. array;forEach(e => { // loop trought let obj = student. e.key.split('.'),forEach((a,bc) => ( // go way trough (obj[a] = b === c?length - 1. e:propertyValue, obj[a] || {}); (obj = obj[a]) // update obj )) }). console.log(student)

或者作为“漂亮”的单线:

array.forEach((e, o) => ((o = student), e.key.split('.').forEach((a,b,c) => ((o[a] = b === c.length - 1 ? e.propertyValue : o[a] || {}), (o = o[a])))));

没有嵌套的 object 这很简单:

arr.reduce((prev, current) => {return prev[current.key] = current.propertyValue}, {})

使用您的数据格式,我将首先执行current.key.split('.') ,然后使用上面的reduce function 递归地构建 object。

您可以结合使用reducesplit来构建 object。

 let arr = [ { key: "name", propertyValue: "Test Name", }, { key: "middleName", propertyValue: null, }, { key: "university.isGraduated", propertyValue: true, }, { key: "university.speciality", propertyValue: "Computer Science", }, { key: "university.country.code", propertyValue: "PL" }]; const result = arr.reduce ( (acc,i) => { const keys = i.key.split("."); let pointer = acc; for(let i=0;i<keys.length-1;i++) pointer = pointer[keys[i]] || (pointer[keys[i]] = {}); pointer[keys[keys.length-1]] = i.propertyValue; return acc; },{}); console.log(result);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM