1

I have the data of the array object in a variable called hi[0].child.

hi[0].child = [
    {code: "food", name: "buger"},
    {code: "cloth", name: "outher"},
    {code: "fruit", name: "apple"},
]

What I want to do is create a variable called hello, change the key value of hi[0].child, and put it in the hello variable.

For example, the key value of code is changed to value and name is changed to label. The values ​​I want are as below.

expecter answer 

hello = [
    {label: "burger", value: "food"},
    {label: "outher", value: "cloth"},
    {label: "apple", value: "fruit"},

]

But when I use my code I get these errors.

Did not expect a type annotation here

so How can i fix my code?

this is my code

let hello = []


hi[0].child.map((v) => {
hello.push(label: v.name, value: v.code)
})
Phil
  • 157,677
  • 23
  • 242
  • 245
user19476497
  • 495
  • 1
  • 10
  • **Just a typo**. You're missing the braces that denote the parameter as an object... `hello.push({label: v.name, value: v.code})` – Phil Jul 29 '22 at 05:00
  • 1
    FYI this might be a little cleaner and actually uses `.map()` for what it's meant for... `const hello = hi[0].child.map(({ name, code }) => ({ label: name, value: code }))` – Phil Jul 29 '22 at 05:02

2 Answers2

3

You've missed the curly brackets for the object, it should be hello.push({ label: v.name, value: v.code }).

Also, map is not the right method to be used here, use forEach instead or use the value returned from map (as shown below).

const data = [
  { code: "food", name: "buger" },
  { code: "cloth", name: "outher" },
  { code: "fruit", name: "apple" },
];

const updatedData = data.map((v) => ({ label: v.code, value: v.name }));

console.log(updatedData);
SSM
  • 2,855
  • 1
  • 3
  • 10
-1

Change the code like this

let hello = []
hi[0].child.map((v) => {
  hello.push({label: v.name, value: v.code})
})

You need to pass object

Badhusha
  • 88
  • 1
  • 1
  • 9
  • `map` returns a modified array, so you should use the returned values instead of pushing to a new array or change the method to `forEach`. Also, `push` can be done on array declared as `const`. – Karin C Jul 31 '22 at 18:04