首页 > 解决方案 > 如何在 javascript 数组中找到对象值?

问题描述

我想要做的是在添加之前检查“内容”是否在我的“篮子”中。

我试过这个,但我不明白为什么它不起作用:

function findById(source, tag, content) {
    for (var i = 0; i < source.length; i++) {
      if (source[i].tag === content) {
        return source[i];
      }
    }
    throw "Couldn't find content ";
  }

这是我使用它的方式:

var basket = {};
var tag = 'someTag';
var content = 'Joe';

const key = randomFunctions.generateRandomString(); // eg ekkciiuekks

// find out if the content is already in the basket...
var result = findById(basket, tag, content);
if(!result){
   // nope... so add it.
   basket[key] = {[tag]:content};
}

附言。我想用纯javascript保留答案

更新

当我将鼠标悬停在长度上时,我正在调试并且得到“未定义”:

source.length

回答

对https://stackoverflow.com/users/7668258/maciej-kocik答案稍作修改,即可:

function findById(source, tag, content) {
    for (let key in source) {
      let property = source[key];
      if(property[tag] === content) {
        return property[tag];
      } 
    }
    return null; // moved this OUTSIDE of for loop
  }

标签: javascript

解决方案


在你的情况下source.length是未定义的。您正在添加一个新的对象属性,而不是一个新的数组项。

尝试类似:

function findById(source, tag, content) {
  for (let key in source) {
    let property = source[key];
    if(property[tag] === content) {
      return property[tag];
    } 
    throw "Couldn't find content";
  }
}

推荐阅读