创建嵌套的JSON对象Javascript

时间:2016-10-05 17:38:57

标签: javascript json rest

您好我想在java脚本的post请求中为存储资源创建一个JSON对象我有一个输入数组值磁盘大小,例如下面:

request1 输入= [10,20,30]

 "storageResources": [
  {
    "stats": [
      {
        "name": "diskSize",
        "units": "GB",
        "value": 10
      },
      {
        "name": "diskIopsConsumed",
        "value": 0
      },
      {
        "name": "diskConsumedFactor",
        "value": 1
      }
    ]
  },
  {
    "stats": [
      {
        "name": "diskSize",
        "units": "GB",
        "value": 20
      },
      {
        "name": "diskIopsConsumed",
        "value": 1
      },
      {
        "name": "diskConsumedFactor",
        "value": "NaN"
      }
    ]
  },
  {
    "stats": [
      {
        "name": "diskSize",
        "units": "GB",
        "value": 30
      },
      {
        "name": "diskIopsConsumed",
        "value": 0
      },
      {
        "name": "diskConsumedFactor",
        "value": 1
      }
    ]
  },
],

请求2: 输入[10,20]

    "storageResources": [
  {
    "stats": [
      {
        "name": "diskSize",
        "units": "GB",
        "value": 10
      },
      {
        "name": "diskIopsConsumed",
        "value": 0
      },
      {
        "name": "diskConsumedFactor",
        "value": 1
      }
    ]
  },
  {
    "stats": [
      {
        "name": "diskSize",
        "units": "GB",
        "value": 20
      },
      {
        "name": "diskIopsConsumed",
        "value": 1
      },
      {
        "name": "diskConsumedFactor",
        "value": "NaN"
      }
    ]
  }
],

使用功能执行此操作的最佳方法是否可以通过属性发送?

1 个答案:

答案 0 :(得分:-1)

使用Array.prototype.map返回修改后的响应



$$text.oninput = evt => {
  let json = JSON.parse($$text.value)
  let result = json.storageResources.map(resource =>
    resource.stats.find(e => e.name == 'diskSize').value
  )
  
  console.log(result)
}

$$text.oninput()

<textarea id="$$text">{"storageResources":[{"stats":[{"name":"diskSize","units":"GB","value":10},{"name":"diskIopsConsumed","value":0},{"name":"diskConsumedFactor","value":1}]},{"stats":[{"name":"diskSize","units":"GB","value":20},{"name":"diskIopsConsumed","value":1},{"name":"diskConsumedFactor","value":"NaN"}]},{"stats":[{"name":"diskSize","units":"GB","value":30},{"name":"diskIopsConsumed","value":0},{"name":"diskConsumedFactor","value":1}]}]}</textarea>
&#13;
&#13;
&#13;