首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript:附加到键的值,其中值是一个列表

Javascript:附加到键的值,其中值是一个列表
EN

Stack Overflow用户
提问于 2019-05-06 02:48:26
回答 1查看 335关注 0票数 2

我将参考以下内容:测试对象物种对象。

在“物种”对象的内部,我有两个属性:“物种”和“状态”。"state“属性有一个值,它是一个带有状态的数组。我想为"test“对象创建一个键,它对应于位于对象物种对象中的" state”数组中的每个状态。

示例输出(查看下面的代码以了解这些值来自何处):

代码语言:javascript
复制
{a: ["tiger", "dog"], b: ["tiger"], c: ["dog","lion"], d: ["tiger", "dog"], e: ["lion:]}

我的想法是,我想列出每个州的物种,而且物种通常不限于一个州,所以肯塔基州的一个物种也可能在俄亥俄州找到。我希望以上述方式将该物种列为这两个州的居民。

我收到的错误如下:

代码语言:javascript
复制
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

这是我的密码:

代码语言:javascript
复制
  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);
      }
    })
  }

如果状态还不存在,我会为它创建一个键。我还首次将该状态的物种的值存储在数组中。当我遇到一个物种生活在一个已经有密钥的状态时,我想把这个物种附加到数组中,这个数组是状态键的值。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-05-06 02:50:09

这是push而不是append

代码语言:javascript
复制
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,如下所示:

代码语言:javascript
复制
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);
代码语言:javascript
复制
.as-console-wrapper { max-height: 100% !important; top: auto; }

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55998210

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档