MLissCetrus
MLissCetrus

Reputation: 463

how do I find an object value in a javascript array?

What I want to do is check if the "content" is in my 'basket' before I add.

I tried this, but I don't understand why it's not working:

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 ";
  }

Here is how I am using it:

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};
}

ps. I would like to keep answer in pure javascript

UPDATE

I am debugging and am getting 'undefined' when I hover over length:

source.length

ANSWER

With a slight modification to https://stackoverflow.com/users/7668258/maciej-kocik answer, this works:

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
  }

Upvotes: 1

Views: 43

Answers (3)

Maciej Kocik
Maciej Kocik

Reputation: 69

The source.length is undefined in your case. You're adding a new object property, not a new array item.

Try something like:

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";
  }
}

Upvotes: 1

Jasdeep Singh
Jasdeep Singh

Reputation: 8301

Use for-in loop to iterate over the objects, we cannot use the traditional for loop. Please find the logic below, i have changed it according to for-in loop.

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

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

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

// 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
  };
}

Upvotes: 0

ray
ray

Reputation: 27245

const hasJoe = Object.values(basket).some( x => x.content === ‘Joe’);

(This isn’t quite right but I’m on my phone and editing is tricky. This is the gist of it. I’ll update when I get to a real keyboard if you don’t have an answer by then.)

Upvotes: 0

Related Questions