1

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 + "]")
    })
0

2 Answers 2

4

You're on the right track with the map() method. The way you've used map() will result in an array of strings. Here's an example of using map() to get the output you requested (new array of objects).

const myObject = {
  "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
    }
  ]
};

const result = myObject.items.map(x => ({ name: x.namezz, data: [x.price] }));

console.log(result);

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

Comments

2

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)

Comments

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.