Ericel Ericel - 3 months ago 8
Javascript Question

What's the difference between this two javascript objects

I am trying to get values from the following object. The for loop works in one of the objects but won't in the other javascript object. I was wondering what the difference and how can I get it to work in the other object?

Object 1:

var objects = [
{
"foo" : "bar",
"bar" : "sit"
},
{
"foo" : "lorem",
"bar" : "ipsum"
}
];


Object 2:

{
"4dd5a49e366": {
"name" : "bar",
"bar" : "sit",
"date": "2016-08-03T04:48:04.283Z"
},
"519c5056af2": {
"name" : "lorem",
"bar" : "ipsum",
"date": "2016-09-03T04:48:04.283Z"
}
}


I want to do a search for items where name attribute is matching some search_term. And return the items.

Here is the search for loops am using.

function searchFor(toSearch) {
var results = [];
toSearch = trimString(toSearch); // trim it
for(var i=0; i<objects.length; i++) {
for(var i in objects[i]) {
if(objects[i][key].indexOf(toSearch)!=-1) {
if(!itemExists(results, objects[i])) results.push(objects[i]);
}
}
}
return results;
}
console.log(searchFor('o'));


This works for the first object and not for the second. How can I get it to work for the second?

Answer

The first variable is an array of objects. Since it is an array you can use all array methods on it.

Second one is an object with keys 4dd5a49e366 & 519c5056af2 which in turn are again object and have few properties.

You cannot use array methods on this second object

how can I get it to work in the other object?

Hope this snippet will be useful

var myObject = {
  "4dd5a49e366": {
    "name": "bar",
    "bar": "sit",
    "date": "2016-08-03T04:48:04.283Z"
  },
  "519c5056af2": {
    "name": "lorem",
    "bar": "ipsum",
    "date": "2016-09-03T04:48:04.283Z"
  }
}
// a function to accept the name value
function findByName(name) {
  var thisObject = "";
  for (var keys in myObject) { // looping over objects
    var getThisObject = myObject[keys];
    if (getThisObject.name === name) { // Checking if name matches
      thisObject = myObject[keys]; // assigning the object to a variable
    }
  }
  return thisObject // return that variable
}
var getMyObject = findByName('bar');
console.log(getMyObject)

JSFIDDLE

EDIT

if I enter just findByName('b'); it should return results that the full name

You need to use indexOf to find if this name value contains the specific character.

Use an array to store all the relevant object where the name value contains this specific character.Return that array from the function.

function findByName(name) {
  var thisObject = [];
  for (var keys in myObject) {
    var getThisObject = myObject[keys];
    if (getThisObject.name.indexOf(name)!==-1) {
      thisObject.push(myObject[keys]);
    }
  }
  return thisObject
}
var getMyObject = findByName('b');

JSFIDDLE 2