【问题标题】:How to combine two different array with different keys into one single array in jquery如何在jquery中将两个具有不同键的不同数组组合成一个数组
【发布时间】:2022-01-24 05:31:44
【问题描述】:

我有两个数组 array1 和数组 2.Array1 的值的键名为“discount_price”,array2 的值​​的键名为“regular_price”。 例如: discount_price_array, regular_price_array

当我使用数组合并合并它们时,我得到一个包含组合值的数组。即如果 array1 有 10 个元素,而 array2 有 10 个元素,它会合并成一个有 20 个元素的数组。 merged_array.

我想要的是一个数组,例如:

array{"discount_price":10,"regular_price":2},
array{"discount_price":4,"regular_price":3},

我怎样才能做到这一点?

  $(values).each(function(key, value) {
  //console.log(value);
  if( value.discount_price !==undefined){
    discount_price_array.push({ discount_price: value.discount_price })
  }
   
    });   
   
$(values).each(function(key, value) {
  //console.log(value);
  if( value.regular_price !==undefined){
    regular_price_array.push({ regular_price: value.regular_price })
  }

    }); 

   var finalarray =$.merge(discount_price_array,regular_price_array 
     )

【问题讨论】:

  • 两个数组的长度一样吗?
  • @SaeedShamloo 是的
  • 可以使用纯js的map或者$.map来代替merge。
  • 欢迎来到 Stack Overflow。你看过api.jquery.com/jquery.extend吗?

标签: javascript jquery


【解决方案1】:

使用map 和“解构(...)”

map:让我们迭代一个数组并返回相同长度的新数组,您可以在其中决定每次迭代将返回什么。

(...) spread ,允许您将(外部属性)属性传播到新对象或数组中,您基本上是将所有对象属性分配给新对象,因为您将两个对象传播到同一个新对象中对象,它们正在被合并。

// if both of them have the same length 

let arr1 = [{'property1': 10 }, {'property1': 10 },];

let arr2 = [{'property2': 20 }, {'property2': 20 },];

let result = arr1.map((object, index)=> ({...object, ...arr2[index] }));
console.log(result);

简单的map only

// if you want to pick which property to assign

let arr1 = [{'property1': 10 }, {'property1': 10 }];

let arr2 = [{'property2': 20 }, {'property2': 20 }];

let result = arr1.map((object, index)=> {
  object['property2'] = arr2[index]['property2'];
  return object; 
});
console.log(result);

【讨论】:

  • 这工作非常感谢你
  • 您能否解释一下您的代码,以便对您有所帮助
  • 添加说明。
猜你喜欢
  • 2016-07-20
  • 2011-04-13
  • 1970-01-01
  • 2020-04-17
  • 2016-04-27
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
  • 1970-01-01
相关资源
最近更新 更多