自学内容网 自学内容网

前端array如何转换为json

原数据数据: [{“templateField”,“name”,“value”: “张三”},{“templateField”,“age”,“value”: “18”}]
希望转换后的数据: {name: “张三”, age: 18}

方案1:

const data =  [{"templateField","name","value": "张三"},{"templateField","age","value": 18}];
const json:any = {};
data.map((item)=>{
  json[String(item.templateField)] = item.value;
  return item;
})
console.log('结果',json); // {name: "张三", age: 18}

方案二:

const data =  [{"templateField","name","value": "张三"},{"templateField","age","value": "18"}];
const json = data.reduce(acc,item)=>{
acc[item.templateField] = item.value;
return acc;
},{});
console.log('结果',json); // {name: "张三", age: 18}

原文地址:https://blog.csdn.net/weixin_43865196/article/details/140368762

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!