jQuery匹配单个数组和对象以及重定义对象值

hrirmatl  于 2023-01-25  发布在  jQuery
关注(0)|答案(1)|浏览(171)

我有两个数组
array_1和array_2。在这里,我想获取与array_1的值匹配的array_2的值。请参见下面的代码

<script>
$(document).ready(function(){
    var array_1 = ['58', '10'];
    var array_2 = {};
    array_2 [0]=  {'id':55, 'name':'raj'};
    array_2 [1]=  {'id':58, 'name':'min'};
    array_2 [2]=  {'id':10, 'name':'max'};
    array_2 [3]=  {'id':12, 'name':'res'};
    
    var size = Object.keys(array_2).length;
    for (z=0; z<size; z++) {
        
        if((array_1[z] !== undefined && array_1[z] !=='') && array_2[z].id == array_1[z]) {
            console.log(array_2[z].id)
        }
    }

});
</script>

这里我需要将array_2作为

array_2[0] = {'id':58, 'name':'min'};
array_2[1] = {'id':10, 'name':'max'};

array_2 = [0=>{'id':58, 'name':'min'}, 1=> {'id':10, 'name':'max'}] ;

请帮助解决此问题

gv8xihay

gv8xihay1#

你可以这样做:

// Initialize an empty object to store the reordered version of array_2
var newArray = {};

// Iterate through each element in array_1
for (var i = 0; i < array_1.length; i++) {
  // Iterate through each element in array_2
  for (var j = 0; j < Object.keys(array_2).length; j++) {
    // Check if the id of the current element in array_2 matches the current element in array_1
    if (array_2[j].id == array_1[i]) {
      // If a match is found, add the element from array_2 to the newArray object with the index from array_1 as the key
      newArray[i] = array_2[j];
    }
  }
}

演示

var array_1 = ['58', '10'];
var array_2 = {};
array_2[0] = {
  'id': 55,
  'name': 'raj'
};
array_2[1] = {
  'id': 58,
  'name': 'min'
};
array_2[2] = {
  'id': 10,
  'name': 'max'
};
array_2[3] = {
  'id': 12,
  'name': 'res'
};

var newArray = {};
for (var i = 0; i < array_1.length; i++) {
  for (var j = 0; j < Object.keys(array_2).length; j++) {
    if (array_2[j].id == array_1[i]) {
      newArray[i] = array_2[j];
    }
  }
}
console.log(newArray);

相关问题