Skip to content Skip to sidebar Skip to footer

Set Array Based On An Array Of Indexes

I want to set a boolean value in a nested object structure, based on a list of indexes The data I want to update looks like this: let categories = [{ 'name': 'Cat 1', 'subs

Solution 1:

You can iterate the given indexes in a loop and at the same time go deeper in your data structure, like in this function:

function setChecked(categories, categoryIndexes) {
    let obj = null;
    for (let index of categoryIndexes) {
        obj = categories[index];
        categories = obj.subs;
    }
    obj.checked = true;
}

let categories = [{"name": "Cat 1","subs": [{"name": "Sub Cat 1.1","subs": [],"checked": false},{"name": "Sub Cat 1.2","subs": [],"checked": false}],"checked": false},{"name": "Cat 2","subs": [],"checked": false}];
setChecked(categories, [0,1]);
console.log(categories);

Solution 2:

You could use reduce to get the last subs up until the last subs and update the checked property

let categories = [{"name": "Cat 1","subs": [{"name": "Sub Cat 1.1","subs": [],"checked": false},{"name": "Sub Cat 1.2","subs": [],"checked": false}],"checked": false},{"name": "Cat 2","subs": [],"checked": false}];
let categoryIndexs = [0, 1];

function update(categories, indices) {
  const last = indices.pop(); // remove the last
  const redued = indices.reduce((acc, i) => acc[i].subs, categories);
  redued[last].checked = true;
  return categories
}

console.log(update(categories, categoryIndexs))

Solution 3:

You could reduce the array by looking to the index of the iteration and take either subs or the item.

const 
    getValue = (subs, indices) => indices.reduce(
        ({ subs }, i) => subs[i],
        { subs }
    );

let categories = [{ name: "Cat 1", subs: [{ name: "Sub Cat 1.1", subs: [], checked: false }, { name: "Sub Cat 1.2", subs: [], checked: false }], checked: false }, { name: "Cat 2", subs: [], checked: false }],
    indices = [0, 1];

console.log(getValue(categories, indices, 'subs'));

Post a Comment for "Set Array Based On An Array Of Indexes"