0

I want to get an object on the basis on ids.I am having object containing key value pairs. Values are in array of objects and i need to manipulate it to get desired result.

This is simple javascript that needs to be manipulated


let myObject = {
   12 : [{
          isAmber : true,
          isBreached : false ,
          priority:"High"
          },
          {
           isAmber : false,
           isBreached : true , 
           priority:"Medium"
          }
       ],
   14 : [{
          isAmber : false,
          isBreached : false ,
          priority:"High"
          },
          {
           isAmber : false,
           isBreached : true , 
           priority:"Low"
          }
       ]
}

Condition : 1)if isAmber == false && isBreached == true result should be "Red"
2)if isAmber == true && isBreached == false result should be "Amber"
3)if isAmber == false && isBreached == false result should be "Green"

I want output like this

{
   12 : {
          status : ["Amber","Red"],
          priority:["High","Medium"]
         },
   14 : {
          status : ["Green","Red"] ,
          priority:["High","Low"]
         }

}
2
  • 1
    Show some code what you have tried till now?? Commented Jul 20, 2019 at 20:09
  • Freecodecamp (freecodecamp.org) has many great javascript lessons, including one about this very specific thing: learn.freecodecamp.org/… Commented Jul 20, 2019 at 20:21

1 Answer 1

1

This is not what I would consider a simple task for a beginner. You need to iterate over the base object and then iterate over the arrays in each child object. From there you need to determine if each element of the array passes your conditions. From there you need to return the results in the desired format.

Here is one possible solution. Though it is not exactly beginner-friendly.

let myObject = {
  12: [{
      isAmber: true,
      isBreached: false,
      priority: "High"
    },
    {
      isAmber: false,
      isBreached: true,
      priority: "Medium"
    }
  ],
  14: [{
      isAmber: false,
      isBreached: false,
      priority: "High"
    },
    {
      isAmber: false,
      isBreached: true,
      priority: "Low"
    }
  ]
}

let results = Object.keys(myObject).map(key => {
  let status = []
  let priority = []

  myObject[key].forEach(({ isAmber, isBreached, priority: elePriority }) => {
    status.push((!!isBreached) ? 'Red' : (!!isAmber) ? 'Amber' : 'Green')
    priority.push(elePriority)
  })
  return { [key]: { status, priority } }
})

console.log(JSON.stringify(results, null, 2))

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

1 Comment

@adiga thanks, I've been meaning to look that up. =)

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.