0

I have an array of objects that I get from an API. The property names are dynamic (meaning I don't have an extensive list of all of them). How can I get an array of all distinct objects? The contract specifies that if key is equal value is also equal. I tried to look around but I found nothing quite like this problem.

[                                                                                                                                                                                           20:31:28
  {
    'product-management': 'Product management'
  },
  {
    'product-development': 'Product development'
  },
  {
    'client-work': 'Client work'
  },
  {
    'client-work': 'Client work'
  },
  {
    'product-development': 'Product development'
  },
  {
    'client-work': 'Client work'
  },
  {
    'product-development': 'Product development'
  }
]
3
  • I would suggest using a different structure, with {key: '…', value: '…' }-shaped objects. Commented Dec 22, 2019 at 22:41
  • can't do that :( Commented Dec 22, 2019 at 22:43
  • 2
    Sure you can. Even if the API responds with this weird JSON, you can still transform it into something more sane locally. Commented Dec 22, 2019 at 22:45

1 Answer 1

1

Spread the array into Object.assign() to merge all objects to a single one. Since all objects properties are unique, this will leave only one key (and value) from the duplicates. Then convert to [key, value] pairs with Object.entries(), and map back to individual objects:

const data = [{"product-management":"Product management"},{"product-development":"Product development"},{"client-work":"Client work"},{"client-work":"Client work"},{"product-development":"Product development"},{"client-work":"Client work"},{"product-development":"Product development"}]

const result = Object.entries(Object.assign({}, ...data))
  .map(([k, v]) => ({ [k]: v }))
  
console.log(result)

Going with @Bergi's suggestion, you can also convert this to a saner API while removing duplicates:

const data = [{"product-management":"Product management"},{"product-development":"Product development"},{"client-work":"Client work"},{"client-work":"Client work"},{"product-development":"Product development"},{"client-work":"Client work"},{"product-development":"Product development"}]

const result = Object.entries(Object.assign({}, ...data))
  .map(([key, value]) => ({ key, value }))
  
console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.