0

I have an array of objects, and analysis is also an array of objects.

const products = [
    {
        id: '111',
        analysis: [
            { id: 1, value: 51 },
            { id: 2, value: 40 },
            { id: 3, value: 25 }
        ]
    },
    {
        id: '222',
        analysis: [
            { id: 1, value: 77 },
            { id: 2, value: 99 },
            { id: 3, value: 22 }
        ]
    }
]

I'm new to immutability-helper. I have an array operations which indicates how to update products array.

const operations = [
    { id: '111', analysisId: 1, value: 10 },
    { id: '111', analysisId: 3, value: 4 },
    { id: '222', analysisId: 3, value: 88 }
];

So this means I want to find the object with id = 111, and then find analysisId = 1, and finally update the value from 51 to 10. Then I will need to do the same thing for the rest 2 operations. I don't want to mutate products array. Would someone help me? Thanks!

1
  • Your products is not initialized as an Immutable object ? Commented Aug 17, 2017 at 11:31

1 Answer 1

3

As far as I know they only way to do it is find the indexes before doing the update

operations.map(operation => {
    var indexOfProduct = products.findIndex(x => x.id === operation.id);
    var indexOfAnalysis = products[indexOfProduct].analysis.findIndex(a => a.id === operation.analysisId);
    products = update(products, {
        [indexOfProduct]: {
            analysis: {
                [indexOfAnalysis]: {
                    value: {$set: operation.value}
                    }                   
                }
            }
        })  
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I couldn't deduct from their docs that we should pass indexOfProduct as [indexOfProduct].

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.