1

My Object nested array is following way,

const values: any = {
    name: '',
    type: undefined,
    references: [
      {
        origin: {
          x1: true,
          x2: '',
          x3: undefined,
        },
      },
      {
        origin: {
          x1: true,
          x2: '',
          x3: undefined,
        },
      },
      {
        origin: {
          x1: true,
          x2: '',
          x3: undefined,
        },
      },
    ],
  };

I want to update x3 field with references array index, How can I achieve this by using ES6 arrow function. I wrote a function but It doesn't work for me. It would be great if someone can correct my function,

 export const replaceReferenceIndex = (values: any) => {
    return {
      ...values,
      references: values.references.map((reference.origin: any, x3: number) => ({
        ...reference.origin,
        x3,
      })),
    };
  };

1 Answer 1

1

You just have to rewrite you map's callback function:

const values = {
    name: '',
    type: undefined,
    references: [
        {
            origin: {
                x1: true,
                x2: '',
                x3: undefined,
            },
        },
        {
            origin: {
                x1: true,
                x2: '',
                x3: undefined,
            },
        },
            {
            origin: {
                x1: true,
                x2: '',
                x3: undefined,
            },
        },
    ],
};
  
const replaceReferenceIndex = (values) => ({
    ...values,
    references: values.references.map((ref, idx) => ({
        ...ref,
        origin: { ...ref.origin, x3: idx }
    })),
});      

console.log(replaceReferenceIndex(values))

I have omitted type annotations since you're obviously don't use them for checking correctness.

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

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.