如何将数组列表格式化为json

时间:2019-03-15 13:54:22

标签: javascript json

我正在尝试从数组列表中获取json对象

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <select ng-options="item.id[0] as item.service[0] for item in items.List" ng-model="selected" ng-change="selectionChanged(selected)"></select>
  
  <div ng-if="selected">
    Selected: <pre ng-bind="selected"></pre>
  </div>
</div>

我已经将上方数组转换为json,如下所示

arrayList [
0: {name: "01", value: "3424234234"} 
1: {name: "17", value: "26021734"}
2: {name: "10", value: "435345"} 
3: {name: "21", value: "3453"}]

我得到的结果如下

var getCode={};
getCode = Object.assign({}, arrayList );

但是我需要如下结果

getCode 
{
0: {name: "01", value: "3424234234"} 
1: {name: "17", value: "26021734"} 
2: {name: "10", value: "435345"} 
3: {name: "21", value: "3453"} 
}

如何获取如上所述的JSON

1 个答案:

答案 0 :(得分:4)

您可以使用Array#reduce方法。

var res = arrayList
  // iterate over the array
  .reduce((obj, o) => {
    // define property 
    obj[o.name] = o.value;
    // return the object
    return obj;
    // set initial value as an empty object
  }, {})

var arrayList = [{
    name: "01",
    value: "3424234234"
  },
  {
    name: "17",
    value: "26021734"
  },
  {
    name: "10",
    value: "435345"
  },
  {
    name: "21",
    value: "3453"
  }
];

var res = arrayList.reduce((obj, o) => {
  obj[o.name] = o.value;
  return obj;
}, {})

console.log(res)


ES6 object destructuring相同。

var res = arrayList.reduce((obj, { name, value }) => {
  obj[name] = value;
  return obj;
}, {})

var arrayList = [{
    name: "01",
    value: "3424234234"
  },
  {
    name: "17",
    value: "26021734"
  },
  {
    name: "10",
    value: "435345"
  },
  {
    name: "21",
    value: "3453"
  }
];

    

console.log(res)

使用spread syntax的单线解决方案:

var res = arrayList.reduce((obj, { name, value }) => ({ [name] : value, ...obj }), {})

var res = arrayList.reduce((obj, { name, value }) => (obj[name] = value, obj ), {})