jquery - Merge two arrays with equal number of objects into one array -


i have 2 arrays filled objects, looks so:

arrayyear:

array [ year: "1977", year: "1980"... ] object { year: "1977" } 

arraymeal:

array [ meal: "carrot", meal: "beef"... ] object { meal: "carrot" } 

how merge 2 arrays 1 looks so?

array [ {year: "1977", meal: "carrot"}, {year: "1980", meal: "beef"}... ] 

the 2 arrays populated so:

arrayyear = []; $('.item-year').each(function(index){     arrayyear.push({ year: $(this).attr('data-year') }); })  arraymeal = []; $('.item-meal').each(function(index){     arraymeal.push({ meal: $(this).attr('data-meal') }); }) 

basically, want extend object. so, jquery has method called .extend. there 1 problem here, have array of object...

to solve issue, have loop array. can use code (read comments understand each lines):

// assign first array  var arr1=[{year:1992},{year:1996},{year:2000}];  // assign second array  var arr2=[{meat:'beef'},{meat:'porc'},{meat:'chicken'},{meat:'robot'}];     // declare resulting array (prevent alterring original arrays)  var merged_arr = []    // loop array  // use math.max work if 1 array has more items  for(var = 0; < math.max(arr1.length, arr2.length); i++){      // set merged_arr cell's 1 new object merge of both objects      // first arg empty object no arrays alterred      merged_arr[i] = $.extend({}, arr1[i], arr2[i]);  }    // alert result  alert(json.stringify(merged_arr))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -