加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

js语法:json数据格式转化

发布时间:2020-12-16 20:01:02 所属栏目:百科 来源:网络整理
导读:json数据格式转化 应用实践能加深对函数接口的理解。 数组如同 星星点点的数据。 对象将它们规整。建立索引关系。 reduce就是两者桥梁 (字符串数组,split,join就是桥梁) map() 是处理变量内部数据转化的。 let arr = [{ 'name': 'level-1','value': 'eve-

json数据格式转化

应用实践能加深对函数接口的理解。

数组如同 星星点点的数据。
对象将它们规整。建立索引关系。

reduce就是两者桥梁(字符串数组,split,join就是桥梁)

map() 是处理变量内部数据转化的。

let arr = [{
    'name': 'level-1','value': 'eve-1','id': 'id-1','parentId': null
},{
    'name': 'level-2','value': 'eve-2','id': 'id-2','parentId': 'id-1'
},{
    'name': 'level-3','value': 'eve-3','id': 'id-3','parentId': 'id-2'
},'value': 'eve-4','id': 'id-4','value': 'eve-5','id': 'id-5','parentId': 'id-4'
}];

let result = arr.reduce(function (prev,item) {
const insert = {
name: item.name,value: item.value,id: item.id
};

prev[item.parentId] ? prev[item.parentId].push(insert) : prev[item.parentId] = [insert];
return prev;

},{});

for (var key in result) {
result[key].forEach(function (item,index) {
result[item.id] ? item.children = result[item.id] : ''
});
}

console.log(JSON.stringify(result[null]));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读