0

I have a set of data, I want to build a new one with custom property name, the existing set of data has nested, that's also one of the reason why I need to normalize it to suite my own use.

says I have this existing set of data

[{
name:"abc",
company:{name:"abc company",age_of_company:1},
age: 19
}]

I want to build a new array of object where the property and nested level will be like this

[{
ceo_name:"abc",
company_name:"abc company",
age: 19
}]

I'm stuck

const newData = existingData.map(obj => (
//obj.company.name I don't know what to do here
)

4 Answers 4

1
const newData = existingData.map(obj => (
    {
        ceo_name: obj.name,
        company_name: obj.company.name,
        age: obj.age
    }
))
Sign up to request clarification or add additional context in comments.

3 Comments

you don't need a return?
The arrow notation automatically returns the value
To be precise, the compact body form of the arrow function automatically returns the value (the form without {}).
1

You can destructure the parameters of the function passed to map as follows:

existingData.map(
  ({age, name: ceo_name, company: {name: company_name}}) =>
    ({ceo_name, company_name, age}))

2 Comments

how about the undefined value? stackoverflow.com/questions/43601425/…
@GialaJefferson What are you worried about being undefined?
0

Try this

[{
    name:"abc",
    company:{name:"abc company",age_of_company:1},
    age: 19
}].map(element => {
    return {
        ceo_name: element.name,
        company_name: element.company.name,
        age: element.age
    }
})

1 Comment

worked, great, but I have another problem now stackoverflow.com/questions/43601425/…
0
const newData = existingData.map(obj => {
  const { name, company, age } = obj;
    return {
      ceo_name: name,
      company_name: company.name,
      age: age
    }
  }
);

2 Comments

is const needed here?
Second line destructures the object so you can avoid repeatedly referencing obj. obj.name becomes name, etc.

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.