JS / JSX获取数组父键或与嵌套项结合使用

时间:2019-01-11 09:15:41

标签: javascript arrays reactjs object jsx

我有以下带有数组的对象:

{
  "brands": [
    "accessible-icon",
    "accusoft",
    "adn",
    "adobe",
    "adversal",
  ],
  "regular": [
    "address-book",
    "address-card",
    "angry",
    "bell",
  ],
  "solid": [
    "ad",
    "address-book",
    "address-card",
    "adjust",
    "air-freshener",
    "align-center",
  ]
}

我有一个函数,可以从数组组之一返回一项。我必须找出从哪个数组组中提取项目。据我了解,无法在js中查找父键?

获取父键将是理想的选择,否则是否可以将父键添加到所有嵌套项目中?例如,brands数组中的嵌套项目将变为:

 "brands": [
    "brands-accessible-icon",
    "brands-accusoft",
    "brands-adn",
    "brands-adobe",
    "brands-adversal",
  ],

然后我可以使用正则表达式提取brands

更多信息:

最初,我将对象转换为具有数组组的对象。这是一个名为brands的对象之一的示例:

{
  "faAccessibleIcon": {
    "prefix": "fab",
    "iconName": "accessible-icon",
    "icon": [
      448,
      512,
      [],
      "f368",
    ]
  },
  "faAccusoft": {
    "prefix": "fab",
    "iconName": "accusoft",
    "icon": [
      640,
      512,
      [],
      "f369",
    ]
  },
  "faAcquisitionsIncorporated": {
    "prefix": "fab",
    "iconName": "acquisitions-incorporated",
    "icon": [
      344,
      512,
      [],
      "f6af",
    ]
  },
}

然后我简化对象:

const array = {
  "brands": Object.keys(brands).map(e=> brands[e].iconName),
  "regular": Object.keys(regular).map(e=> regular[e].iconName),
  "solid": Object.keys(solid).map(e=> solid[e].iconName),
};

然后array成为在我的问题顶部看到带有数组的对象。数组结构必须保持这样。有没有一种方法可以为每个数组组组合prefixiconName并在嵌套数组项中获取brands-accessible-iconbrands-accusoft等?

3 个答案:

答案 0 :(得分:3)

您可以获取对象的键并在数组中找到值。

const getKey = (object, value) => Object.keys(object).find(k => object[k].includes(value));

var data = { brands: ["accessible-icon", "accusoft", "adn", "adobe", "adversal"], regular: ["address-book", "address-card", "angry", "bell"], solid: ["ad", "address-book", "address-card", "adjust", "air-freshener", "align-center"] };

console.log(getKey(data, "bell"));

答案 1 :(得分:1)

我认为有一个简单的答案。

const array = {
  "brands": Object.keys(brands).map(e=> "brands-"+brands[e].iconName),
  "regular": Object.keys(regular).map(e=> "regular-"+regular[e].iconName),
  "solid": Object.keys(solid).map(e=> "solid-"+solid[e].iconName),
};

答案 2 :(得分:1)

你在这里。

通过获取对象的条目,然后映射每个对象以将其父对象的名称添加到其字符串中,可以创建所需的输出。

(除非我误解了您的问题,因为每个答案似乎都有不同之处)

工作示例:

<div class="slidecontainer">
  <p>Custom range slider:</p>
  <input type="range" min="1" max="100" value="50" class="slider" id="myRange">
</div>