Search code examples
javascriptarraysjsonjavascript-objects

copy from one object, change keys but keep the same values


Hi I want to copy a JavaScript object that lives in an external json file. It looks like this:

and via the code I want to change the keys on each array without changing the values of it. The values for the last key needs be an array instead of just vales

{ "items": [
  { "namezz": "Bike", "price": 100 },
  { "namezz": "TV", "price": 700 },
  { "namezz": "Album", "price": 10 },
  { "namezz": "Book", "price": 5 },
  { "namezz": "Phone", "price": 500 },
  { "namezz": "Computer", "price": 1000 },
  { "namezz": "Keyboard", "price": 25 }
]
}

It needs to looks like this:

[
  { "name": "Bike", "data": [100] },
  { "name": "TV", "data": [700] },
  { "name": "Album", "data": [10] },
  { "name": "Book", "data": [5] },
  { "name": "Phone", "data": [500] },
  { "name": "Computer", "data": [1000] },
  { "name": "Keyboard", "data": [25] }
]

code that I've tried:

 const itemNames =  simple.map((xxx) => {

        return ("name" + xxx.namezz + "data: [" + xxx.price + "]")
    })

Solution

  • Problem with your code is returning string whereas you need a object, i.e

    return { name:xxx.namezz , data: [xxx.price] }
    

    Alternatively you can use map and destructuring

    let obj = { "items": [{ "namezz": "Bike", "price": 100 },{ "namezz": "TV", "price": 700 },{ "namezz": "Album", "price": 10 },{ "namezz": "Book", "price": 5 },{ "namezz": "Phone", "price": 500 },{ "namezz": "Computer", "price": 1000 },{ "namezz": "Keyboard", "price": 25 }]}
    
    let final = obj.items.map(({ price, namezz }) => ({ namezz, data: [price] }))
    
    console.log(final)