gpt4 book ai didi

javascript - 将属性附加到图例的有效方法

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

我正在开发一个应用程序 - 它将循环数据 - 我想将一个属性附加到现有图例 - 不使用两个 for 循环。

let listRegions = [{
"label" : "A",
"value" : "SIEA"
},{
"label" : "E",
"value" : "SIEE"
},{
"label" : "JA",
"value" : "SIEJA-JAPAN"
},{
"label" : "AS",
"value" : "SIEJA-ASIA"
}];

本质上 - 当它遇到一行数据时 - 我想克隆这个数组 - 并将 isInincluded 属性添加到每个值 - 但如果找到,则将 isInincluded 设置为 true

let newList= [{
"label" : "A",
"value" : "SIEA",
"isIncluded": true
},{
"label" : "E",
"value" : "SIEE",
"isIncluded": false
},{
"label" : "JA",
"value" : "SIEJA-JAPAN",
"isIncluded": false
},{
"label" : "AS",
"value" : "SIEJA-ASIA",
"isIncluded": false
}];
<小时/>

类似这样的东西 https://jsfiddle.net/eb2zx70m/1/

let listRegions = [{
"label": "A",
"value": "SIEA"
}, {
"label": "E",
"value": "SIEE"
}, {
"label": "JA",
"value": "SIEJA-JAPAN"
}, {
"label": "AS",
"value": "SIEJA-ASIA"
}];

console.log("listRegions", listRegions);

var regions = ["SIEJA-ASIA", "SIEE"];
console.log("regions", regions);

for (var i = 0; i < regions.length; i++) {


let legendRegions = [];
listRegions.forEach(function(e) {
console.log("regions[i]", regions[i]);
console.log("e.value", e.value);

if (e.value === regions[i]) {
console.log("e.value", e.value);
e.enabled = true;
} else {
e.enabled = false;
}
legendRegions.push(e);

console.log("newList", legendRegions);
});



};

最佳答案

试试这个:

// N list regions
const listRegions = [{
"label": "A",
"value": "SIEA"
}, {
"label": "E",
"value": "SIEE"
}, {
"label": "JA",
"value": "SIEJA-JAPAN"
}, {
"label": "AS",
"value": "SIEJA-ASIA"
}];

// K regions
const regions = ["SIEJA-ASIA", "SIEE"];
// complexity O(K)
const includedRegions = regions.reduce((res, region) => ({
...res,
[region]: true
}), {});

// complexity O(N)
const newList = listRegions.map(region => ({
...region,
isIncluded: !!includedRegions[region.value]
}));

// total complexity O(N + K)
console.log(newList);

这里是相同的解决方案,但没有声明额外的 regionsInincluded map 。该映射作为 thisArg 传递到 Array.map()功能:

// N list regions
const listRegions = [{
"label": "A",
"value": "SIEA"
}, {
"label": "E",
"value": "SIEE"
}, {
"label": "JA",
"value": "SIEJA-JAPAN"
}, {
"label": "AS",
"value": "SIEJA-ASIA"
}];

// K regions
const regions = ["SIEJA-ASIA", "SIEE"];

// complexity O(N) and O(K) for thisArg value
const newList = listRegions.map(region => ({
...region,
isIncluded: Boolean(this[region.value])
}), regions.reduce((res, region) => ({
...res,
[region]: true
}), {}));

// total complexity O(N + K)
console.log(newList);

关于javascript - 将属性附加到图例的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59934553/

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