键匹配时替换数组的值?

时间:2019-11-19 10:36:48

标签: javascript reactjs

当键匹配时,我的实际代码没有推送对象,但是当键匹配时,如何更新键的值?

this.state.data.concat(items).filter(function (a) {
    return !this[a.key] && (this[a.key] = true);
}, Object.create(null))

1 个答案:

答案 0 :(得分:0)

// some object we want to change
const items = {
  a: true,
  b: false,
  v: true,
  g: true
};
// some value we want to match with object key
let someKeyWeWantToMatch = "b";
// for of loop
for (let [key, value] of Object.entries(items)) {
  // if key matches...
  if (key === someKeyWeWantToMatch) {
    // ...change its value
    items[key] = true;
  }
}
// and we are done
console.log(items);

/* 
EXPLANATION:
Objects are not iterable, so if we want to iterate throught them we have to make an Map out of them
We do this with: Object.entries(objectName)
So object goes from this:
{a:'aaa'}
Into this:
['a','aaa']

Then we can easily check the value of its key, and change it if we want.
 */