netchi
netchi

Reputation: 67

Looping through JSON objects in Array

I am trying to loop over this array with objects but I believe I am missing something. Basically I am checking to see if my fav array has the "text" keyword from the companies array. The final JSON object should be like shown below (The JSON object is two companies since Ford was not present in the fav array). What am I missing in my solution https://jsfiddle.net/netchi/rsam2k9h/5/

{ 
  text: "Toyota",
  origin: "Japan",
  icon: "icon"
},
{
 text: "Honda",
 models: "12",
}

Upvotes: 0

Views: 85

Answers (4)

Mr Khan
Mr Khan

Reputation: 2292

You are not adding them to the array with index because adding values using dot usually signifies object keys. By pushing the values in the array, they are added as indexes and now you can loop throught them. Below you can see if we use dot to insert into an array, it converts into an object and you can identify it using typeof.

enter image description here

The correct way is to use push method to insert data into array.

var companies = [];
var fav = ["Toyota", "Honda"];

companies.push({
  text: "Toyota",
  origin: "Japan",
  icon: "icon"
})


companies.push({
  text: "Ford",
  founder: "Henry Ford",
  icon: "icon"
})

companies.push({
  text: "Honda",
  models: "12"
})

//check if fav includes the text from companies array. If it does then push JSON
let finalJson = [];
    console.log(companies)
  companies.forEach(company => {
    console.log(company)
    if (fav.includes(company.text)) {
      finalJson.push(company);
    }
  });

console.log(companies, finalJson);

if you wish to loop over with object key, there are several ways you can do this with the Es

for (const value of Object.values(companies)) {
    console.log(value.text);
 }

or with Es6

Object.keys(companies).forEach(e => console.log(`${e}`));

Upvotes: 3

Yevhen Horbunkov
Yevhen Horbunkov

Reputation: 15550

Your problem seems to be defining companies as an object (using dot notation to assign its properties, that correspond to company names), but later on you attempt to apply Array.prototype.forEach() which will not work for objects.

Instead, (if companies in deed was intended to be an object) you need to extract its values (with Object.values()) and apply Array.prototype.filter() together with Array.prototype.includes() to extract data by text values present in fav:

const fav = ["Toyota", "Honda"],
      companies = {Toyota:{text:"Toyota",origin:"Japan",icon:"icon"},Ford:{text:"Ford",founder:"Henry Ford",icon:"icon"},Honda:{text:"Honda",models:"12"}}
      
      result = Object.values(companies).filter(({text}) => fav.includes(text))
      
console.log(result)
.as-console-wrapper{min-height:100%;}

But, as long as companies is in fact an object with company names as its keys, you may use that directly:

const fav = ["Toyota", "Honda"],
      companies = {Toyota:{text:"Toyota",origin:"Japan",icon:"icon"},Ford:{text:"Ford",founder:"Henry Ford",icon:"icon"},Honda:{text:"Honda",models:"12"}}
      
      result = Object
        .entries(companies)
        .reduce((r,[companyName,companyData]) => 
          (fav.includes(companyName) && r.push(companyData), r), [])
      
console.log(result)
.as-console-wrapper{min-height:100%;}

However, if your initial intention was to have companies as an array (not an object) you may apply filter() right away:

const fav = ["Toyota", "Honda"],
      companies = [{text:"Toyota",origin:"Japan",icon:"icon"},{text:"Ford",founder:"Henry Ford",icon:"icon"},{text:"Honda",models:"12"}]
      
      result = companies.filter(({text}) => fav.includes(text))
      
console.log(result)
.as-console-wrapper{min-height:100%;}

Upvotes: 1

Srividhya
Srividhya

Reputation: 389

https://jsfiddle.net/srividhyar25/t1urg9kw/16/

you have to use the object if you want to use the 'Honda', 'Toyato' as keys. or You should push the objects to companies.

var companies = {};
var fav = ["Toyota", "Honda"];

companies['Toyota'] = {
  text: "Toyota",
  origin: "Japan",
  icon: "icon"
};

companies['Ford'] = {
  text: "Ford",
  founder: "Henry Ford",
  icon: "icon"
};

companies['Honda'] = {
  text: "Honda",
  models: "12"
};

//check if fav includes the text from companies array. If it does then push JSON

let finalJson = [];
  for(const company in companies) {
    if (fav.includes(company)) {
      finalJson.push(companies[company]);
    }
  }

console.log(finalJson);

Upvotes: 1

Robert Feduș
Robert Feduș

Reputation: 311

This is the code you're looking for:

var fav = ["Toyota", "Honda"];
var companies = [
Toyota = {
  text: "Toyota",
  origin: "Japan",
  icon: "icon"
},

Ford = {
  text: "Ford",
  founder: "Henry Ford",
  icon: "icon"
},
Honda = {
  text: "Honda",
  models: "12"
}]

//check if fav includes the text from companies array. If it does then push JSON
let finalJson = [];
  companies.forEach(company => {
    if (fav.includes(company.text)) {
      finalJson.push(company);
    }
  });

console.log(finalJson);

The problem was you were trying to loop through an object instead of an array with the forEach method. So i remade the "companies" array the correct way.

Upvotes: 3

Related Questions