Extract an arrays of objects into one array using ES6

extract object from array javascript
extract data from array javascript
lodash
javascript object to array of values
destructuring array of objects
es6 destructuring object
es6 get first element of array
javascript extract part of object

I am working on ReactJS project and have the following JSON data:

[
  {
    "sources": [
      {
        "sourceName": "test_demographics",
        "table": "test_demographics_summary"
      }
    ],
    "userId": "test",
    "queryType": {
      "mixedQuery": false,
      "queryTable": "test_a_query"
    }
  },
  {
    "sources": [
      {
        "sourceName": "something_demographics",
        "table": "something_demographics_summary"
      },
      {
        "sourceName": "something_demographics",
        "table": "something_demographics_summary"
      }
    ],
    "userId": "test",
    "queryType": {
      "mixedQuery": false,
      "queryTable": "test_bquery"
    }
  }
]

I want to extract all the objects in the sources property into one array with deduped data. So essentially for the above JSON data I want an array like so:

[
  {
    "sourceName": "test_demographics",
    "table": "test_demographics_summary"
  },
  {
    "sourceName": "something_demographics",
    "table": "something_demographics_summary"
  }
]

Appreciate any suggestions.

Since javascript compares objects by reference you need to invent a way to compare by value. One way is to serialize the objects and store the serialized version in a set. Here you can serialize by taking the Object.entries(), sorting on keys, and JSON.stringify them. Once you've done that, it's just a matter of looping through and adding what you haven't seen to the set and output. Something like:

let arr = [{"sources": [{"sourceName": "test_demographics","table": "test_demographics_summary"}],"userId": "test","queryType": {"mixedQuery": false,"queryTable": "test_a_query"}},{"sources": [{"sourceName": "something_demographics","table": "something_demographics_summary"},{"sourceName": "something_demographics","table": "something_demographics_summary"}],"userId": "test","queryType": {"mixedQuery": false,"queryTable": "test_bquery"}}]

function getUniqueSources(arr){

    let seen = new Set // holds serialized object

    return arr.reduce((arr, item) => {
        item.sources.forEach(source =>{
            // need to sort so key order doesn't matter for equality
            let serial = JSON.stringify(Object.entries(source).sort((a, b) => a[0].localeCompare(b[0])))
            if (!seen.has(serial)) {
                seen.add(serial)
                arr.push(source)
            }
        })
        return arr

    },[])
}

console.log(getUniqueSources(arr))

ES6: Destructuring, One of the new features is the ability of destructuring arrays and objects. This is an easy and convenient way of extracting data from arrays and objects. Let's take a Next, let's use destructuring to extract data from the array. ES6: Destructuring — an elegant way of extracting data from arrays and objects in JavaScript. ES6 is full of treats. Its additions really improve the coding experience in JavaScript and once again shows that JavaScript is here to stay. One of the new features is the ability of destructuring arrays and objects. This is an easy and convenient way of extracting data from arrays and objects.

If you think you would have various data types and the objects in sources wound not have different order of their props then you can use Set with Array.reduce and JSON.stringify to convert them into strings for comparison:

const data = [ { "sources": [ { "sourceName": "test_demographics", "table": "test_demographics_summary" } ], "userId": "test", "queryType": { "mixedQuery": false, "queryTable": "test_a_query" } }, { "sources": [ { "sourceName": "something_demographics", "table": "something_demographics_summary" }, { "sourceName": "something_demographics", "table": "something_demographics_summary" } ], "userId": "test", "queryType": { "mixedQuery": false, "queryTable": "test_bquery" } } ]

const exists = (s, v) => {
  const json = JSON.stringify(Object.entries(v))
  return s.has(json) ? true : (s.add(json), false)
}
const getUniques = arr => {
  let merged = data.reduce((r,c) => [...r.sources, ...c.sources]), s = new Set()	
  return merged.reduce((r,c) => !exists(s, c) ? (r.push(c), r) : r, [])
}
console.log(getUniques(data))

Extract Data from Arrays and Objects in JavaScript, Extract Data from Arrays and Objects in JavaScript using destructuring. It is a simple javascript expression, that unpacks values from an array or object. Here​, multiple data getting assigned in a single declaration. iterating through complex objects in a loop, all can be handled using ES6 destructuring. Why are objects not iterable by default? I see questions all the time related to iterating objects, the common solution being to iterate over an object's properties and accessing the values within

I ended up doing the following:

    // extract sources arrays
    let sources = queryObjects.map(function (queryObject) {
        return queryObject.sources;
    })

    // add sources objects into one array and remove duplicates
    let sourcesArray = sources.reduce((acc, currValue) => {
        return _.uniq(acc.concat(currValue));
    })

Destructuring Arrays & Objects: JavaScript ES6 Feature Series (Pt 10), The destructuring assignment, first introduced with ES 2015, is one of values from arrays, or properties from objects, into distinct variables. Array destructuring was introduced and finalized into the ECMAScript new arrays and objects within them so I could show how you can pull values out of either. obj.roles[0] is a object {"name":"with whom"}. you cant replace string with object. you need to refer to property "name" in the object obj.roles[0].name Another problem is that var finalXML get a new value every line. you need to add a new value to the variable, not replcae it. var finalXML

Extracting Nested Data from Complex Objects with a Single Line of , semantic way to extract the data you need from an object or array with a single things like skip specific elements or slice arrays into pieces like this: The new destructuring syntax was added to JavaScript as part of ES6,  Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information. Learn more ES6 map an array of objects, to return an array of objects with new keys [duplicate]

Converting Object to an Array, We have 3 variations to convert an Object to an Array in JavaScript. Ancient times; ES6 - Object.keys; Object.values; Object.entries; Object.entries + all your wish 🧞‍♀️. you can now easily extract the values into an array with one method. Merge Arrays in one with ES6 Array spread. Raw. gistfile1.txt. const arr1 = [1,2,3] const arr2 = [4,5,6] const arr3 = [arr1, arr2] //arr3 ==> [1,2,3,4,5,6] This comment has been minimized. Sign in to view. Copy link.

How to Use Array and Object Destructuring in JavaScript, How to Use Array and Object Destructuring in JavaScript The destructuring assignment is a cool feature that came along with ES6. Destructuring is a That is, we can extract data from arrays and objects and assign them to variables. Notice that instead of having just one comma, we have three. Destructuring Objects and Arrays in ES6. In this article, we will learn about destructuring objects and arrays in ES6. We will also have a look into the JavaScript REST operator. So, let's give it a go. To follow along with the code snippets, you can use an online editor.

Comments
  • What determines they are duplicates? All key/values match?
  • Can we see your attempt to solve?