使用lodash更新对象数组的值

时间:2017-09-28 02:20:53

标签: javascript lodash

我的状态对象是:

[
    {
        traveller1_dob: '',
        traveller1_firstName:'',
        traveller1_isPreviousTraveller: false,
        traveller1_surname:'',
        traveller1_title: ''
    },
    {
        traveller2_dob: '',
        traveller2_firstName:'',
        traveller2_isPreviousTraveller: false,
        traveller2_surname:'',
        traveller2_title: ''
    }

]

我的有效负载是:

{key: "traveller1_firstName", value: "ABC", index: 0}
  • key是需要更新的对象的属性
  • value:是我们要更新的值
  • index:是状态数组中的旅行者的索引

目前这是我更新的方式:

let obj = state[payload.index];
obj[payload.key] = payload.value;

return _.unionBy(state, [obj], payload.key);

我知道这不是最好的方法。

输出应为:

[
    {
        traveller1_dob: '',
        traveller1_firstName:'ABC',
        traveller1_isPreviousTraveller: false,
        traveller1_surname:'',
        traveller1_title: ''
    },
    {
        traveller2_dob: '',
        traveller2_firstName:'',
        traveller2_isPreviousTraveller: false,
        traveller2_surname:'',
        traveller2_title: ''
    }

]

理想情况下,如果可能,我想摆脱索引。你会怎么做?

1 个答案:

答案 0 :(得分:2)

你是对的,你可以摆脱索引,只需映射你的状态并检查每个stateItem上的hasOwnProperty并将它们与payload.key进行比较。下面的代码段可以解决您的问题:

let state = [{
        traveller1_dob: '',
        traveller1_firstName: '',
        traveller1_isPreviousTraveller: false,
        traveller1_surname: '',
        traveller1_title: ''
    }, {
        traveller2_dob: '',
        traveller2_firstName: '',
        traveller2_isPreviousTraveller: false,
        traveller2_surname: '',
        traveller2_title: ''
    }

];


function updateState(payload) {

    const updatedState = _.map(state, stateItem => {
        if (stateItem.hasOwnProperty(payload.key)) {
            stateItem[payload.key] = payload.value;
        }
        return stateItem;
    });

    console.log(updatedState);
    return updatedState;
}

const samplePayload = {
    key: "traveller1_firstName",
    value: "ABC",
    index: 0
};

updateState(samplePayload);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>