首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当key匹配时替换数组的值吗?

当key匹配时替换数组的值吗?
EN

Stack Overflow用户
提问于 2019-11-19 18:36:49
回答 1查看 201关注 0票数 0

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

代码语言:javascript
运行
复制
this.state.data.concat(items).filter(function (a) {
    return !this[a.key] && (this[a.key] = true);
}, Object.create(null))
EN

回答 1

Stack Overflow用户

发布于 2019-11-19 21:01:41

代码语言:javascript
运行
复制
// 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.
 */
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58932025

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档