skip to Main Content

How to loop through an array of object got similar key and different value for Example if,

arrayOfObjects = [
{ parent: 'relatedParty', child: 'role === CEO', andOr = '&&' }
{ parent: 'relatedParty', child: 'name === Arun' , andOr = '||'}
{ parent: 'relatedParty', child: ' id === 123', andOr = '&&' }
{ parent: 'cusotm', child: 'contact === DAP', andOr = '||' }
{ parent: 'custom', child: 'team==dap', andOr = '&&' }
{ parent: 'multiple', child: 'key ===keys', andOr = '||' }
{ parent: 'multiple', child: 'value=== values', andOr = '&&' }
]. 

im stuck in a position where how can i iterate through this and get output like if
first object of parent is === second object, then I want them to add into an array and finally those values should be inside another array

[[role === CEO && name === Arun && id === 123 &&], [contact === DAP || team==dap && ],[ key ===keys || value=== values &&]]

2

Answers


  1. Your example is not a valid array, are you getting it from somewhere else, like a http request?

    Anyway, after fixing it to a valid array, you can try grouping by parent, and them mapping the values into what you need.

    Grouping could be like:

    const grouped = {}
    arrayOfObjects.forEach(obj => {
      if (!grouped[obj.parent]) {
        grouped[obj.parent] = []
      }
      grouped[obj.parent].push(obj)
    })
    

    You can also use reduce, or other ways to group by parent.

    After it, just map the values into what you want:

    const result = Object.values(grouped).map(group => {
      return group.map(obj => `${obj.child} ${obj.andOr}`).join(' ')
    })
    

    If you need it in string format to send to some api, do it like:

    const body = JSON.stringify(result)
    
    Login or Signup to reply.
  2. Here is a more concise way to handle your problem:

    const arrayOfString = arrayOfObjects.reduce((acc, {parent, child, andOr}) => {
        const value = `${child} ${andOr}`
      acc[parent] = acc[parent] ? [`${acc[parent] || ''} ${value}`] : [`${value}`]
        return acc
    },  {})
    
    const result = Array.from(Object.values(arrayOfString))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search