gpt4 book ai didi

javascript - 如何拼接javascript中的项目列表?

转载 作者:行者123 更新时间:2023-11-30 12:22:44 27 4
gpt4 key购买 nike

我有以下内容:

list1 = [{letter:'A'}, {letter:'B'}, ..., {letter:'Z'}]

我想遍历列表并向此 list2: ['A', 'C','Z'] 中的所有值添加键值 "special":"yes"

我想要的最终目标是结果列表:

list1 = [{letter:'A'}, {letter:'C'}, {letter:'Z'}]

我该怎么做?

我尝试遍历 list1,检查是否在 list2 中,如果不在,则从中拼接一个元素,但它不起作用,因为所有索引都发生了变化。拼接不是我想要的吗?我应该怎么做?

最佳答案

这里有两件事要做,所以让我们把它们分解一下:

  • 过滤不在其他列表中的键
  • 将一个键加到其他键上

你有一个数组,所以过滤很容易:

list1 = [{letter:'A'}, {letter:'B'}, ..., {letter:'Z'}]

filtered = list1.filter(function (el) {
return list2.indexOf(el.letter) !== -1;
});

现在我们要添加其他键,Array.prototype.map 来拯救:

final = filtered.map(function (el) {
el.special = 'yes';
return el;
});

Array.map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

数组过滤器:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

希望对您有所帮助!

关于javascript - 如何拼接javascript中的项目列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30471064/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com