用新值替换数组中的现有对象

时间:2020-08-05 22:26:09

标签: javascript oop ecmascript-6

我有多个下拉菜单,我试图更新对象的值(如果它存在于数组中)

我的onChange如下

          onChange={e => {
            const answer = {
              id: questionChoice.id,
              name: questionChoice.text,
              value: e,
            }
            let newAnswer = {
              ...currentAnswer,
            }

            if (!currentAnswer.value) {
              newAnswer.value = [] // init empty array
            }

            if (index in newAnswer.value) {
              console.log('found')
              console.log('here', index in newAnswer.value)
              newAnswer.value = newAnswer.value.filter(item => item.value !== answer.value)
            }

            newAnswer.value = [...newAnswer.value, { [questionChoice.text]: answer.value }]
            console.log('new answer', newAnswer)

            updateCurrent(newAnswer)
          }}
          optionFilterProp="children"
          onFocus={onFocus}
          onBlur={onBlur}
          filterOption={(input, option) =>
            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
          }
        >
         

我当前的输出是这个

newAnswer.value: [
0: {Inform producers about the range of sustainability practices: "1"}
1: {Inform producers about environmental management: "7"}
2: {Provide mentoring services to new advisors: "12"}
3: {Inform producers about the range of sustainability practices: "2"}
]

预期输出为

newAnswer.value: [
0: {Inform producers about the range of sustainability practices: "2"}
1: {Inform producers about environmental management: "7"}
2: {Provide mentoring services to new advisors: "12"}
]

现在,它会附加来自newAnswer.value = [...newAnswer.value, { [questionChoice.text]: answer.value }]的任何新结果

但是我找到正确的对象

if (index in newAnswer.value) {
                  console.log('found')
                  // replace object here
                  newAnswer.value = newAnswer.value.filter(item => item.value !== answer.value)
               }

只是不确定如何在适当位置更改特定对象

2 个答案:

答案 0 :(得分:0)

您可以使用Array#find查找对象并在之后更新属性值。

const value = [{
  'Inform producers about the range of sustainability practices': "1"
}, {
  'Inform producers about environmental management': "7"
}, {
  'Provide mentoring services to new advisors': "12"
}];
let questionChoice = 'Inform producers about the range of sustainability practices';
let newAnswer = '2';
let obj = value.find(o => o.hasOwnProperty(questionChoice));
if(obj != null) obj[questionChoice] = newAnswer;
console.log(value);

答案 1 :(得分:0)

想通了,

已更改

newAnswer.value = [...newAnswer.value, { [questionChoice.text]: answer.value }]

newAnswer.value[index] = { [questionChoice.text]: answer.value }

相关问题