azowad
azowad

Reputation: 23

How To Use An Array Of Object Outside For Loop Created In The For Loop?

I am a newbie in Javascript. So, forgive me for any mistakes related to terminology. I have created an array inside a for loop. Here is the code. Whenever I use console outside the condition and loop only a single line is shown. I have updated the question and added the array. I want to select the array which has rice and see it outside of the for loop.

enter image description here

I need to see like this whenever I use console outside the loop: enter image description here

  const datastructure= [

    {"months":"January","productname":"Rice","production":"10","hector":"2"},
    {"months":"February","productname":"Rice","production":"11","hector":"2"},
    {"months":"March","productname":"Rice","production":"12","hector":"2"},
    {"months":"April","productname":"Rice","production":"13","hector":"2"},
    {"months":"January","productname":"Fruit","production":"14","hector":"2"},
    {"months":"February","productname":"Fruit","production":"15","hector":"2"},
    {"months":"Markch","productname":"Fruit","production":"16","hector":"2"},
    {"months":"April","productname":"Fruit","production":"16","hector":"2"},

];
for(i in datastructure){
  if(datastructure[i].productname=="Rice")
  {
  var months=datastructure[i].months
  var  productname=datastructure[i].productname
  var  production=datastructure[i].production
  var  hector=datastructure[i].hector



formatedata =[({'months':months, 'productname':productname,'production':production,'hector':hector})];


 console.log(formatedata)
  }


}

Upvotes: 1

Views: 331

Answers (2)

A1exandr Belan
A1exandr Belan

Reputation: 4780

I think you need to use .filter instead of a for loop

const datastructure= [ 
  {"months":"January","productname":"Rice","production":"10","hector":"2"},
  {"months":"February","productname":"Rice","production":"11","hector":"2"},
  {"months":"March","productname":"Rice","production":"12","hector":"2"},
  {"months":"April","productname":"Rice","production":"13","hector":"2"},
  {"months":"January","productname":"Fruit","production":"14","hector":"2"},
  {"months":"February","productname":"Fruit","production":"15","hector":"2"},
  {"months":"Markch","productname":"Fruit","production":"16","hector":"2"},
  {"months":"April","productname":"Fruit","production":"16","hector":"2"}
];

const riceProducts = datastructure.filter(({ productname }) => productname === 'Rice');

riceProducts.forEach(( product )=> console.log(product));

// or just 
// console.log(riceProducts)
.as-console-wrapper { max-height: 100% !important; top: 0 }

Upvotes: 1

cesium133
cesium133

Reputation: 67

You will have to push to the formatedata array instead of reassigning it

Upvotes: 0

Related Questions