[英]How to merge multiple objects
Hello I am new in react native and I want to merge data using Object.assign()
.您好,我是 react native 的新手,我想使用
Object.assign()
合并数据。
I tried with simple arrays and everythings work but my array is more than array in one big array.我尝试使用简单的 arrays 并且一切正常,但我的阵列不仅仅是一个大阵列中的阵列。
My code:我的代码:
let o1 = getCartData; // [{productId:56, productQuantity:1}, {productId:4, productQuantity:1}]
let o2 = resultObject; // product with different quantity {productId:56, productQuantity:5}
let finalObj = Object.assign([], o1, o2);
console.log('Final', finalObj); // Output ▼["[","{",""","p","r","o","d","u","c","t","I","d",""",":","5","6",",",""","p","r","o","d","u","c","t","Q","u","a","n","t","i","t","y",""",":","1","}","]"]
I want to get this output:我想得到这个 output:
console.log('Final', finalObj); // Merged [{productId:56, productQuantity:5}, {productId:4, productQuantity:1}]
You can map
it, Please let me know if this is what you need:你可以
map
它,如果这是你需要的,请告诉我:
var obj1=[{productId:56, productQuantity:1}, {productId:4, productQuantity:1}]; var obj2={productId:56, productQuantity:5}; var result = obj1.map(({productId, productQuantity})=>({ productId, productQuantity: obj2[`productId`]==productId? obj2.productQuantity: productQuantity})); console.log(result);
Or you can make use of reduce
method to group data:或者您可以使用
reduce
方法对数据进行分组:
var obj1=[{productId:56, productQuantity:1}, {productId:4, productQuantity:1}]; var obj2={productId:56, productQuantity:5}; var result = [...obj1, obj2].reduce((acc, {productId, productQuantity})=>{ acc[productId] = acc[productId] || {productId, productQuantity}; acc[productId].productQuantity = productQuantity; return acc; },{}); console.log(Object.values(result));
You can do this using map and find:您可以使用 map 执行此操作并找到:
arr1.map(arrObj => arr2.find(arr2Obj => arr2Obj.productId === arrObj.productId) || arrObj);
What this code does is:这段代码的作用是:
Notice that this code works for comparing two arrays, in your example you are trying to compare an array with an object, it can be easily solved if your o2 is equal to [resultObject] (Inside the [brackets] to turn it into an array).请注意,此代码适用于比较两个 arrays,在您的示例中,您尝试将数组与 object 进行比较,如果您的 o2 等于 [resultObject](在 [brackets] 内将其转换为数组)。
Got this solution from here: Replacing objects in array从这里得到这个解决方案: 替换数组中的对象
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.