1

Hi I have a list of objects. I want to create a new instance of these objects to update one value.

const arr = [
  { data: { name: "first", type: "child" } },
  { data: { name: "second", type: "parent" } },
];

I would like to have an array of the same objects, but whose type would be upper case like below:

const arr = [
  { data: { name: "first", type: "CHILD" } },
  { data: { name: "second", type: "PARENT" } },
];

I map this array and return new mapped objects, I can add new prop to an object but I can not find a way to change data.type. Here is my piece of code:

const a = arr.map(e => {
    return Object.assign({},e,{data['type']:'???'}
});

3 Answers 3

3

How about this way?

const arr=[{data:{name:'first',type:'child'}},{data:{name:'second', type:'parent'}}]
const a = arr.map(e => {
  let data = {...e["data"], type: e["data"].type.toUpperCase()};
  return ({...e, data});
});
console.log(a);

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

1 Comment

with a slight modification it was what I needed, thanks;)
3

Using map:

const result = data.map(({ data }) => ({ data: { ...data, type: data.type.toUpperCase() }}));

const data = [{data:{name:'first',type:'child'}},{data:{name:'second', type:'parent'}}]

const result = data.map(({ data }) => ({ data: { ...data, type: data.type.toUpperCase() }}));

console.log({result})

2 Comments

Please check the input/output again
The objects are supposed to have a data property
3

You don't need to use Object.assign:

const arr = [
  { data: { name: "first", type: "child" } },
  { data: { name: "second", type: "parent" } },
];

const a = arr.map(e => ({
    data: {
       name: e.data.name,
       type: e.data.type.toUpperCase()
    }
}))

console.log(a)

6 Comments

I use object assign because i'm adding some new values to them
yes and I want new array of objects with 'modified' values. Of course original array has to stay untouched
That's the purpose of map. It does exactly what you want to do. Try my code
This code will never work. Try to run and you will got TypeError: e.type is undefined
|

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.