我将引用以下内容: 测试对象 物种对象。
在“species”对象内部,我有两个属性:“species”和“state”。 “state”属性的值是一个包含状态的数组。 我想为“测试”对象创建一个键,该键对应于位于对象物种对象中的“状态”数组内的每个状态。
示例输出(查看下面的代码以了解这些值的来源):
{a: ["tiger", "dog"], b: ["tiger"], c: ["dog","lion"], d: ["tiger", "dog"], e: ["lion:]}
我的想法是,我想列出每个州内的物种,而物种通常不限于单个州,因此肯塔基州的一个物种也可能在俄亥俄州发现。我希望该物种以上述方式被列为两个州的居民。
我收到的错误如下:
Uncaught (in promise) TypeError: test[d].append is not a function
at script.js:272
at Array.forEach (<anonymous>)
at runVis (script.js:270)
at script.js:178
这是我的代码:
var test = new Object();
var species = [{species: "tiger", state: ["a","b","d"]},
{species: "dog", state: ["a","c","d"]},
{species: "lion", state: ["c", "e"]}
];
for (i in species) {
species[i].state.forEach(function(d) {
if (d in test) {
test[d].append(species[i].species)
}
else {
test[d] = [species[i].species];
console.log(test);
}
})
}
如果状态尚不存在,我会为其创建一个 key 。我还第一次将该状态的物种值存储在数组中。当我遇到一个生活在已经有 key 的状态的物种时,我想将该物种附加到数组中,该数组是状态 key 的值。
最佳答案
这是push
而不是append
:
for (i in species) {
species[i].state.forEach(function(d) {
if (d in test) {
test[d].push(species[i].species)
} else {
test[d] = [species[i].species];
console.log(test);
}
})
}
您还可以使用 reduce
代替,如下所示:
var species = [{species: "tiger", state: ["a","b","d"]},{species: "dog", state: ["a","c","d"]},{species: "lion", state: ["c", "e"]}];
var test = species.reduce((acc, { species, state }) => {
state.forEach(s => {
acc[s] = acc[s] || [];
acc[s].push(species);
});
return acc;
}, {});
console.log(test);
.as-console-wrapper { max-height: 100% !important; top: auto; }
关于Javascript:附加到键的值,其中该值是一个列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55998210/