gpt4 book ai didi

JavaScript:关于 JSON 数据操作的 2 个问题

转载 作者:行者123 更新时间:2023-12-02 17:25:25 25 4
gpt4 key购买 nike

我有两个对象数组:

data = [
{"value": 10.2, "cat": "A", "state": "MA"},
{"value": 5.3, "cat": "B", "state": "MA"},
{"value": 20.1, "cat": "A", "state": "NY"},
{"value": 17.3, "cat": "B", "state": "NY"},
{"value": 7.7, "cat": "A", "state": "CT"},
{"value": 11.3, "cat": "B", "state": "CT"}
];

reference = [
{"state": "MA", "increment": 4.1},
{"state": "NY", "increment": 0.3},
{"state": "CT", "increment": 20.6}
];

问题

  1. 我怎样才能拉出所有state来自 reference 的字段没有循环?具体来说,像这样的函数 reference.pullElement("state")返回类似 ["MA", "NY", "CT"] 的内容。这存在吗?我是否必须创建一个 reference对象并将以下逻辑构建到方法中?

    var states = [];
    for (var i = 0; i < reference.length; i++) {
    states.push(reference[i]["state"]);
    }

  2. 如何添加 increment来自 reference 的字段至value领域 data ,这样我就可以有一个像这样的新数组。

    output = [
    {"value": 14.3, "cat": "A", "state": "MA"},
    {"value": 9.4, "cat": "B", "state": "MA"},
    {"value": 20.4, "cat": "A", "state": "NY"},
    {"value": 17.6, "cat": "B", "state": "NY"},
    {"value": 28.3, "cat": "A", "state": "CT"},
    {"value": 31.9, "cat": "B", "state": "CT"}
    ];

我正在尝试对问题 2 执行以下操作,但实际数据的类别比这多得多。这是最有效的方法吗?

var output = data.slice();
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < reference.length; j++) {
if (data[i]["state"] == reference[j]["state"]) {
output[i]["value"] = data[i]["value"] + reference[j]["increment"];
}
}
}

谢谢!

最佳答案

如果您能够使用数组上现在可用的(相对较新的)方法,则可以执行以下操作。

1.

// Produce an array of state strings
var states = reference.map(function(el) { return el.state; });

2.

// Produce an object with state strings as keys and increments as the values
var stateIncMap = reference.reduce(function(items, item) {
items[item.state] = item.increment;
return items;
}, {});

// Here's an alternate version of the above, using forEach() instead of reduce():
// var stateIncMap = {};
// reference.forEach(function(el) {
// stateIncMap[el.state] = el.increment;
// });

// Update elements' values using the increments
data.forEach(function(el) {
el.value += stateIncMap[el.state];
});

http://jsfiddle.net/vY5Sr/

关于JavaScript:关于 JSON 数据操作的 2 个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23550380/

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