Ask Your Question
3

What is the process to remove duplicate nested data in ES5.6?

asked 2022-04-02 11:00:00 +0000

woof gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-03-17 13:00:00 +0000

nofretete gravatar image

Assuming you want to remove duplicate objects from an array that has nested objects, you can use the following process in ES5.6:

  1. First, convert the array into a string using JSON.stringify().
  2. Use a loop or any library function to remove duplicates from the converted string.
  3. Convert the cleaned-up string back to an array using JSON.parse().

Here's an example code snippet:

var data = [
  { name: "John", age: 25, address: { city: "New York", country: "USA" } },
  { name: "Jane", age: 30, address: { city: "London", country: "UK" } },
  { name: "John", age: 25, address: { city: "New York", country: "USA" } }
];

var stringifiedData = JSON.stringify(data);
var uniqueString = [...new Set(stringifiedData)];
var uniqueData = JSON.parse(uniqueString);
console.log(uniqueData); //[{name: "John", age: 25, address: { city: "New York", country: "USA" }}, {name: "Jane", age: 30, address: {city: "London", country: "UK"}}]

Note that this approach relies on the string representation of the objects within the array. As a result, it may not work effectively with complex objects containing functions, Date objects or circular references.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-04-02 11:00:00 +0000

Seen: 8 times

Last updated: Mar 17 '23