【问题标题】:Alternatives for forEach when returning values looping through object返回值循环通过对象时 forEach 的替代方案
【发布时间】:2021-05-16 12:58:28
【问题描述】:

我希望从forEach 返回,但forEach 不允许使用return 命令。

我有一个函数,我想传递一个object 和一个key。我想遍历该对象,直到某个键与函数参数中的键匹配,然后返回该键的值。

我已经建立了这个:

const iterate = (o, k) => Object.keys(o).forEach((key) => {
  if (key === k) { console.log(o[key]); return o[key]; }
  if (typeof o[key] === 'object') { iterate(o[key], k); }
  return { "message": "error" };
});

(async () => {
  const obj = { x1: { y1: { z1: 'a1' } } }; const keys = 'y1';
  const data = await iterate(obj, keys);
  console.log(data);
  return data;
})();

但是底部的data 是未定义的。我认为问题是forEach 不允许return 语句。有人可以为此用例推荐更好的方法吗?

【问题讨论】:

  • 使用.map() 而不是.forEach() 将项目返回到新数组中。
  • 找到密钥后使用some 提前退出。
  • @ScottMarcus 我尝试以.map() 开头,再次,它仍然返回 undefined ,除非它是数组中的父元素。
  • @gorak 我以为.some() 只能返回真/假,而不是对象的值?

标签: javascript node.js arrays loops object


【解决方案1】:

找到匹配项后使用some 提前退出。

const obj = { x1: { y1: { z1: 'a1' } } };

const getValue = (obj, key)=>{
 var result;
 (returnKey=obj=>{
    return Object.entries(obj)
      .some(([k,v])=> k==key && (result=v) ? true : 
       typeof  v=="object" && returnKey(v))
 })(obj);
 return result;
}
 

console.log(getValue(obj, 'y1'));

【讨论】:

  • 有没有办法在returnKey函数中自我包含结果,所以函数返回值vs将值分配给函数范围之外的值?如果它可以做到这一点,我会将这个答案标记为正确的,因为这就是我正在寻找的:)
  • @user3180997 更新了我的答案。看看吧。
【解决方案2】:

你说得对——forEach 不支持返回值(返回值无处可去)。

传统的for 循环可能是这里最简单的解决方案,我们只想返回第一个找到的值:

const iterate = (o, k) => {
  const keys = Object.keys(o);
  for (let i = 0; i < keys.length; i += 1) {
    const key = keys[i];
    if (key === k) { // we found it!
      return { found: true, value: o[key] }; 
    }

    if (typeof o[key] === 'object') { // we haven't found it, but it could be in here:
      const deeperIterationResult = iterate(o[key], k);
      if (deeperIterationResult.found) {
        return deeperIterationResult;
      }
    }
  }

  // it was nowhere in o:
  return { found: false };
};

const iterateOrError = (o, k) => {
  const result = iterate(o, k);

  if (result.found) {
    return result.value;
  }

  return { "message": "error" };
};

(async () => {
  const obj = { x1: { y1: { z1: 'a1' } } }; const keys = 'y1';
  const data = await iterateOrError(obj, keys);
  console.log(data);
  return data;
})();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-15
    • 2018-07-02
    • 2017-11-06
    • 2016-11-16
    • 1970-01-01
    • 2018-06-06
    相关资源
    最近更新 更多