1
\$\begingroup\$

Is there a more idiomatic way to handle the following scenario? I'm open to lodash, etc. if needed. This does what I want, but I feel that there is probably a shortcut I'm missing:

const migrateValues = (obj, srcKey, destKey, value) => {
    updatedSrc = [];
    obj[srcKey].forEach(x => {
        if (x !== value) {
            updatedSrc.push(x);
        }
    });
    obj[destKey].push(value);
    obj[srcKey] = updatedSrc;
    return obj;
}

obj = {
    "key1": [1, 2, 3],
    "key2": [4, 5, 6],
    "key3": [7, 8, 9],
    "key4": [10, 11, 12]
};
valueToMove = 11;
srcKey = "key4";
destKey = "key2";

console.log(obj);
console.log(migrateValues(obj, srcKey, destKey, valueToMove));
\$\endgroup\$
  • \$\begingroup\$ This assumes no empty lists, no dupes, etc. \$\endgroup\$ – JacobIRR Feb 17 at 1:10
3
\$\begingroup\$

I would propose something like so (given that you have assumed no dupes, etc)

function migrateValues(obj, srcKey, destKey, value) {
    return {
        ...obj,
        [srcKey]: obj[srcKey].filter(w => w !== value),
        [destKey]: obj[destKey].concat(value)
    };
}

We spread obj, and then overwrite the srcKey and destKey properties.

There are several reasonable ways to make obj[srcKey].filter and obj[destKey].concat avoid TypeErrors, which is best is dependent on what you have planned for the function.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thanks, I like the key override pattern you've used \$\endgroup\$ – JacobIRR Feb 18 at 18:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.