Javascript:将JSON数据存储在数组中

时间:2018-11-19 17:11:20

标签: javascript json

我有这样的JSON。

[{
    "address": "A-D-1",
    "batch": [{
        "batch_number": "B-123",
        "cost": [{
            "cost": "C1"
        }]
    }]
},
{
    "address": "A-85-1",
    "batch": [{
        "batch_number": "B-6562",
        "cost": [{
            "cost": "C16464"
        }]
    }]
},
{
    "address": "A-522-1",
    "batch": [{
        "batch_number": "B-4511",
        "cost": [{
            "cost": "C8745"
        }]
    }]
}]

我想将JSON数据存储到数组中。

let data = JSON.parse('[{"address":"A-D-1","batch":[{"batch_number":"B-123","cost":[{"cost":"C1"}]}]},{"address":"A-85-1","batch":[{"batch_number":"B-6562","cost":[{"cost":"C16464"}]}]},{"address":"A-522-1","batch":[{"batch_number":"B-4511","cost":[{"cost":"C8745"}]}]}]');

for (let i = 0; i < data.length; i++) {

if (data[i].batch !== undefined && data[i].batch !== null && data[i].batch.length !== undefined && data[i].batch.length > 0) {
  let batchLength = data[i].batch.length

  let newObject = {}
  let newArray = []

  for (let j = 0; j < batchLength; j++) {
    if (data[i].batch !== undefined && data[i].batch[j].cost !== null && data[i].batch[j].cost.length !== undefined && data[i].batch[j].cost.length > 0) {
      let costLength = data[i].batch[j].cost.length
      for (let k = 0; k < costLength; k++) {

        newObject.location = data[i].address
        newObject.batch.number = data[i].batch[j].batch_number ? data[i].batch[j].batch_number : ''

        newObject.cogs = data[i].batch[j].cost[k].cost ? data[i].batch[j].cost[k].cost : ''
        newArray.push(newObject)
      }
    }
  }
}

}

我已将JSON存储在data变量中。

我尝试了以下代码。但是我总是得到上一个索引作为重复索引。

预期输出:

[
   {
      "address":"A-D-1",
      "batch":{
         "batch_number":"B-123"
      },
      "cost":"C1"
   },
   {
      "address":"A-85-1",
      "batch":{
         "batch_number":"B-6562"
      },
      "cost":"C16464"
   },
   {
      "address":"A-522-1",
      "batch":{
         "batch_number":"B-4511"
      },
      "cost":"C8745"
   }
]

任何帮助都会很棒。

谢谢。

2 个答案:

答案 0 :(得分:0)

您的意思是这样的吗?

const someArray = [{
  "address": "A-D-1",
  "batch": [{
    "batch_number": "B-123",
    "cost": [{
      "cost": "C1"
    }]
  }]
}, {
  "address": "A-85-1",
  "batch": [{
    "batch_number": "B-6562",
    "cost": [{
      "cost": "C16464"
    }]
  }]
}, {
  "address": "A-522-1",
  "batch": [{
    "batch_number": "B-4511",
    "cost": [{
      "cost": "C8745"
    }]
  }]
}]

console.log(someArray.map(item => {
return {
address:item.address,
batch_number: item.batch && item.batch[0].batch_number,
cost: item.batch && item.batch[0].cost[0].cost
}
}))

答案 1 :(得分:0)

您可以使用以下方法以数组格式检索相同的内容。

const data = JSON.parse(someArray);
console.log (data[0].address);