gpt4 book ai didi

javascript - 循环 JSON 并添加新的键值数据

转载 作者:行者123 更新时间:2023-12-03 05:00:54 26 4
gpt4 key购买 nike

我有一个像这样的大 json 数据集:

{
"10001": {
"coords": [
"40.753793,-74.007026/40.750272,-74.00828",
"40.751445,-74.00143/40.752055,-74.000975",
"40.751439,-73.99768/40.752723,-73.99679"
],
"meta": {
"city": "New York",
"state": "NY",
"latCenter": 40.71,
"lngCenter": -73.99
}
},
"10002": {
"coords": [
"40.714069,-73.997504/40.709181,-73.996222/40.709485,-73.994022"
],
"meta": {
"city": "New York",
"state": "NY",
"latCenter": 40.71,
"lngCenter": -73.99
}
},
and so on....
}

我需要在“meta”类别中添加新的“key”:“value”数据。我尝试使用 JSON.parse 将其转换为 JavaScript 对象,但它不起作用。它说 JSON 格式不正确。即使在转换之后,如何通过循环实际访问元部分并在其中添加新值,同时保留旧的格式和数据?

最佳答案

const data = {
"10001": {
"coords": [
"40.753793,-74.007026/40.750272,-74.00828",
"40.751445,-74.00143/40.752055,-74.000975",
"40.751439,-73.99768/40.752723,-73.99679"
],
"meta": {
"city": "New York",
"state": "NY",
"latCenter": 40.71,
"lngCenter": -73.99
}
},
"10002": {
"coords": [
"40.714069,-73.997504/40.709181,-73.996222/40.709485,-73.994022"
],
"meta": {
"city": "New York",
"state": "NY",
"latCenter": 40.71,
"lngCenter": -73.99
}
}
};

// inject key "hello" with value "world"
Object.keys(data).forEach(key => Object.assign(data[key].meta, { "hello": "world" }));

console.log(data);

关于javascript - 循环 JSON 并添加新的键值数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42230839/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com