遍历JSON仅更新单个元素

时间:2018-09-27 20:17:10

标签: javascript json

我有以下JSON。我将如何在纯JavaScript中对此进行迭代以仅更新bCoordinates的坐标?

    { aCoordinates: { latitude: 22.572646, longitude: 88.36389500000001 },
  bCoordinates: { latitude: 22.572646, longitude: 88.36389500000001 } }

2 个答案:

答案 0 :(得分:1)

为什么要迭代?只需直接访问它即可:

url_to_scrape = 'http://www.presidency.ucsb.edu/ws/index.php?pid=119039'
req = urllib.request.Request(url_to_scrape)
resp = urllib.request.urlopen(req)
resp.read()

答案 1 :(得分:0)

由于您的数据存储在密钥对对象中, 您真的不需要迭代。

// you could use Object Spread Operator if supported by your runtime
const update = (data, id, field, value) => Object
  .assign({}, data, {
    [id]: Object.assign({}, data[id], { [field]: value }),
  })
;

const data =   { 
  aCoordinates: { 
    latitude: 22.572646, 
    longitude: 88.36389500000001,
  },
  bCoordinates: { 
    latitude: 22.572646, 
    longitude: 88.36389500000001,
  },
}

const data2 = update(data, 'bCoordinates', 'longitude', 2.9);

// console.log('data', data);
console.log('data2', data2);