简体   繁体   中英

how to print given array in for each using javascript

I have an array like below.

[{
  'i_id':'119',
  'name':'Brinjal-250',
  'weight':'250.Gm',
  'qty':'1',
  'price':'5',
  'market':'55',
  'image':'f_control/images/vegetables/Brinjal-PNG-Image-min'
 },   
 {  
  'i_id':'101',
  'name':'Tomato',
  'weight':'500.Gm',
  'qty':'1',
  'price':'4',
  'market':'44',
  'image':'f_control/images/vegetables/tometo-min.jpg'
}]

And i want it to in for each loop using java script, It is possible? If possible then please guide me in right direction, Thanks.

The demo output 在此处输入图片说明

Why are you using different array for each object ? You can push both objects in a single array , then you can use forEach loop like this :-`

var array = [
    {
        'i_id':'119',
        'name':'Brinjal-250',
        'weight':'250.Gm',
        'qty':'1',
        'price':'5',
        'market':'55',
        'image':'f_control/images/vegetables/Brinjal-PNG-Image-min'
    },
    {
        'i_id':'101',
        'name':'Tomato',
        'weight':'500.Gm',
        'qty':'1',
        'price':'4',
        'market':'44',
        'image':'f_control/images/vegetables/tometo-min.jpg'
    }
    ];
        array.forEach(function(value){
            console.log(value.name);
        });`

If both objects are in the same array, just like below:

[{'i_id':'119',
'name':'Brinjal-250',
'weight':'250.Gm',
'qty':'1',
'price':'5',
'market':'55',
'image':'f_control/images/vegetables/Brinjal-PNG-Image-min'},
{'i_id':'101',
    'name':'Tomato',
    'weight':'500.Gm',
    'qty':'1',
    'price':'4',
    'market':'44',
    'image':'f_control/images/vegetables/tometo-min.jpg'}]

then use:

arrayName.forEach(function (item, index) {
  console.log(item["name"]);
})

or else use:

for(var key in arrayName) {
   console.log("key: "+key+" Value: "+arrayName[key]["name"]);
}

Check out the fiddle : https://jsfiddle.net/NayanaDas/42f3yxho/

Updated Answer:

if you want to make this array [{'i_id':'101'}] [{'i_id':'102'}] like this [{'i_id':'101'},{'i_id':'102'}] , then use JavaScript Array concat() Method :

var arr1 = [{'i_id':'101'}];
var arr2 = [{'i_id':'102'}];

var array = arr1.concat(arr2);

console.log(JSON.stringify(array));

See the fiddle : https://jsfiddle.net/NayanaDas/eaumhnvw/

The requirement is not clear. If you want to loop through he array use forEach or conventinal for-loop will also work.

var myArray=[//json array]
myArray.forEach(function(item,index){
  console.log(item.name) // will seperately log Brinjal-250, & Tomato
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM