简体   繁体   English

如何根据给定的索引更新嵌套数组中的值并在javascript中返回原始数组?

[英]How to update a value in nested array based on the given index and return original array in javascript?

I have an index '3_1_0' and the following array:-我有一个索引“3_1_0”和以下数组:-

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所以 3_1_0 将提取以下内容

{
    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.将 d2.1 中的值更新为其他值,例如“new_d2.1”,并将更新后的值附加到原始字段数组中的相同索引处,并返回更新后的字段数组。 How this can be done?如何做到这一点?

You can use Array.reduce to get the desired result.您可以使用Array.reduce来获得所需的结果。 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').我们将使用一些Optional Chaining来确保如果没有找到值,我们将返回undefined (假设我们的索引是“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);

 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM