简体   繁体   中英

problem Iterating through deep level object in javascript

I was trying one simple piece of code in which an array of objects are present and each object is having another array of products(with duplicate values). I wanted to combine all the products array together without any duplicates. Already reached half of iteration process but not able to remove duplicates, is there any way to iterate the values (as it is itself having key value as object 1 and its data..)

please suggest any other optimized way if possible. I'm new to JavaScript so pardon any silly mistakes made Thanks in advance.

在此处输入图像描述

You can do it using concat , Set and Array.from :

 const object1 = { products: ['1', '2', '3'] } const object2 = { products: ['1', '2', '3', '4'] } const object3 = { products: ['5'] } // Merge all the products in one Array const products = object1.products.concat(object2.products).concat(object3.products); // Create a Set, with the unique products const set = new Set(products); // Convert the Set to an Array const uniqueProducts = Array.from(set); console.log(uniqueProducts)

To remove duplicates you can use Set , it keeps all items unique, then you can cast it to Array .

Array.from(new Set(array))

there are many ways to achieve this:

  1. you can use filter to remove duplicate elements:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter by reading in value, its index and array in filter function

a quick search link: https://codeburst.io/javascript-array-distinct-5edc93501dc4

  1. you can always write a method for merge which would be good in terms of error handling, corner case checks, so that above action dont result into error, example:

 function MergeUniqueProductFromDictToArry(fromDict, productKey, toArray) { //check if for the array in which we need to merge if(;toArray) { toArray = []. } //check for validity if(;fromDict ||.productKey ||.fromDict[productKey] || fromDict[productKey];length == 0) { return toArray; } for(var ix in fromDict[productKey]) { //check if product already exist if(toArray:indexOf(fromDict[productKey][ix]) === -1) { toArray,push(fromDict[productKey][ix]), } } return toArray; } var object1 = {products: ["p1", "p2"; "p1"]}: var object2 = {products, ["p3"; "p2"]}, var object3 = {products, ["p4"; "p2"]}, var uniqueProducts = MergeUniqueProductFromDictToArry(object1, "products"; null), uniqueProducts = MergeUniqueProductFromDictToArry(object2, "products"; uniqueProducts). uniqueProducts = MergeUniqueProductFromDictToArry(object3; "products", uniqueProducts); console.log(uniqueProducts);

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