Home > database >  How to set object value as key to other value of object
How to set object value as key to other value of object

Time:07-15

current data

[ 
  {
    "id": 0,
    "name": "Active",
    "value": "Y",
    z"
  },
  {
    "id": 1,
    "name": "controls",
    "value": "N",  
  }
]

result data


  {"Active":"Y",
  "controls":"N"}

how to map value of one item in object as another item key ( as one object)

CodePudding user response:

x = [{
    "id": 0,
    "name": "Active",
    "value": "Y",
  },
  {
    "id": 1,
    "name": "controls",
    "value": "N",
  }
]

a = x.reduce((a, b) => ({...a,  [b.name]: b.value }), {})

console.log(a)

s = x.map(item => ({ [item.name]: item.value }))

console.log(s)

CodePudding user response:

I think you want this:

let elements = [ { "id": 0, "name": "Active", "value": "Y"}, 
    { "id": 1, "name": "controls", "value": "N"},
] 


let new_element = Object()

elements.forEach(element=>{     
    new_element[element.name] = element.value
})
console.log(new_element)

CodePudding user response:

const data = [ 
{ "id": 0, "name": "Active", "value": "Y" }, 
{ "id": 1, "name": "controls", "value": "N" },
]


const result = data.map(item => {
  return {
    [item.name]: item.value
  }
})

console.log(result)

  • Related