0

I have an index '3_1_0' and the following array:-

var fields = [
    {
        name: 'a'
    },
    {
        name: 'b'
    },
    {
        name: 'c'
    },
    {
        name: 'd',
        fields: [
            {
                name: 'd1'
            },
            {
                name: 'd2',
                fields: [
                    {
                        name: 'd2.1'
                    }
                ]
            }
        ]
    }
]

I need to extract the element from the above fields array based on the index. so 3_1_0 will extract following

{
    name: 'd2.1'
}

Update the value from d2.1 to some other value like 'new_d2.1' and attach the updated value at the same index in original fields array and return the updated fields array. How this can be done?

2 Answers 2

2

You can use Array.reduce to get the desired result. We start by splitting the index into an array, then reducing to get the result.

We'll use some Optional Chaining to ensure we'll return undefined if no value is found (say our index was '7_10_20').

Once we've found our object, we can set the required property.

const fields = [ { name: 'a' }, { name: 'b' }, { name: 'c' }, { name: 'd', fields: [ { name: 'd1' }, { name: 'd2', fields: [ { name: 'd2.1' } ] } ] } ];

const index = '3_1_0'

function setValue(fields, index, property, value) {
    const obj = index.split('_').reduce((acc, key) => { 
       return acc?.[key] || acc?.fields?.[key];
    }, fields);
    // Only update if we actually find anything
    if (obj) { 
        obj[property] = value
    }
}

setValue(fields, '3_1_0', 'name', 'new_d2.1');

console.log("Fields:", fields);

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

5 Comments

I never notice arr["0"] is implicitly converted as the arr[0].
It's effectively the same thing I believe, one would have to look at the ECMA spec. to see exactly how it should be handled. One could always do a .map after the split like index.split('_').map(n => +n), but I don't think it's strictly necessary.
Thanks for the answer, I am looking to get the original array back with name updated to new_d2.1 at 3_1_0 position
@TerryLennox, Yes. They are the same thing, even happen in the object. I just never notice it before.
Appreciate the feedback @D.K. I've updated!
0

const data = [{ name: 'a' }, { name: 'b' }, { name: 'c' }, { name: 'd', fields: [ { name: 'd1' }, { name: 'd2', fields: [ { name: 'd2.1' } ] } ] } ];

let givenIdxs = "3_1_0";

let indexes = givenIdxs.split("_");

let result = data[indexes[0]];

for(let idx = 1; idx < indexes.length; idx++){
  result = result.fields[indexes[idx]];
}

console.log(result);

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.