Programmer21 Programmer21 - 1 year ago 83
Node.js Question

How to loop objects in javascript

I have collection of Object like this

{
adHorizontalPosition: { right: 1, middle: 2, left: 3 },
adSiteZonesFormat: { smallBanner: 1, bigBanner: 2 },
adVerticalPosition: { bottom: 1, middle: 2, top: 3 },
border: { none: 1, Solid: 2 },
campaignDestinationType: { url: 1, tag: 2, script: 3 }
}


but i want one that user enters and make it like this

or example if user enters "border" than output will be like this

[{
_id:0,
name: "none"
}, {
_id:1,
name: "Solid"
}]


How can I achieve this?

Answer Source

Here's some simple code that will work. Loop through the property's keys and push your desired format into a new array, and return it.

const obj = { 
  adHorizontalPosition: { right: 1, middle: 2, left: 3 },
  adSiteZonesFormat: { smallBanner: 1, bigBanner: 2 },
  adVerticalPosition: { bottom: 1, middle: 2, top: 3 },
  border: { none: 1, Solid: 2 },
  campaignDestinationType: { url: 1, tag: 2, script: 3 }
}

const modifiedObj = (property) => {
  let newArr = [];
  let i = 0;
  for (var key in obj[property]) {
    newArr.push({
      _id: i,
      name: key
    })
    i++
  }
  return newArr
}

console.log(modifiedObj("border"))

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download