【问题标题】:How can I get values of array out of object in array?如何从数组中的对象中获取数组的值?
【发布时间】:2022-11-17 05:23:04
【问题描述】:

我正在建造一个战舰版本,其中船是蠕虫,玩家是鸟……如果这能解释事物的命名。

我有一个时刻。我需要遍历嵌套坐标数组的值,但我就是想不通。

这是数组的样子:

[{"grub": [23, 24]}, {"earthworm": [34, 35, 36]}, {"larvae": [77, 78, 79]}]

我需要遍历所有嵌套对象,然后遍历该嵌套对象内的数组以查看输入是否与值匹配。

函数输入将是一个带 2 位数字的坐标(例如“84”)

输出应该是一个布尔值,说明坐标是否存在于作为对象值的任何数组中。

我有很多想法,但没有一个成功。

【问题讨论】:

  • 请展示您尝试过的想法以及它们是如何失败的。
  • 那个数据结构看起来很奇怪,为什么你不能使用一个单一的对象?
  • 通常,每个对象中具有不同键的对象数组是一个糟糕的主意。使用单个对象或具有一致键的对象数组,例如{name: "grub", coordinates: [23, 24]}

标签: javascript arrays object iteration


【解决方案1】:

const data = [{"grub": [23, 24]}, {"earthworm": [34, 35, 36]}, {"larvae": [77, 78, 79]}];

const f=(n,data)=>data.map(Object.values).some(([i])=>i.includes(n));

console.log(f(35, data));
console.log(f(84, data));

【讨论】:

    【解决方案2】:

    我会用Array.prototype.some

    const array = [{"grub": [23, 24]}, {"earthworm": [34, 35, 36]}, {"larvae": [77, 78, 79]}]
    
    handleInput()
    
    document.querySelector('input').addEventListener('input', ({ target: { value } }) => handleInput(value))
    
    function handleInput(value) {
      const isItem = isValueInNestedArray(+value, array)
      document.querySelector('p').textContent = isItem ? 'yes' : 'no'
    }
    
    function isValueInNestedArray(value, array) {
      return array.some(item => Object.values(item).some(arr => arr.some(coord => coord === value)))
    }
    <input>
    <p></p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-20
      • 1970-01-01
      • 1970-01-01
      • 2019-09-19
      • 2017-07-09
      相关资源
      最近更新 更多