【问题标题】:How do I find a certain value and replace it in and push all the values in a new array?如何找到某个值并将其替换为新数组中的所有值?
【发布时间】:2021-06-29 21:24:29
【问题描述】:

我对 Javascript 有非常基本的了解。我正在编写一个插件来搜索一些预定义的颜色并用新颜色替换它们。到目前为止,我能够获得一个包含颜色、名称和样式的数组作为数组内的对象。

现在我想搜索某种颜色,例如 - eb40a2 并将其替换为 ffffff 并将这个新值推送到新数组中。

var ref=[];
....

ref.push({ name: styleName, color: styleColor, parent: styleParent, styles: styleId });

这给了我以下数组:

0: {name: "pink_theme/dark/fill/active", color: "eb40a2", styles: "S:5bebabedaa118ab6d135df59d7ba8861c05992a0,5:1"}
1: {name: "green_theme/light/fill/product", color: "c85200", styles: "S:380f15d999c08d9d97725c9915f479e52c1a343c,244:13"}
2: {name: "green_theme/light/fill/active", color: "00880d", styles: "S:b2aecc5927c659d7fba7d021b092bc90618043a5,189:0"}
3: {name: "green_theme/light/fill/product", color: "0081a0", styles: "S:1f28c38bfa1b10ca61aeaf706ac2a71fa6425950,244:11"}

【问题讨论】:

  • 必须是新数组吗?为什么不只更新当前位置的颜色
  • 你能帮我把它更新到当前位置吗?

标签: javascript arrays object replace find


【解决方案1】:

您可以映射数组并有条件地更新您想要的颜色。检查下面的代码sn-p:

const arr = [
  {
    name: 'pink_theme/dark/fill/active',
    color: 'eb40a2',
    styles: 'S:5bebabedaa118ab6d135df59d7ba8861c05992a0,5:1',
  },
  {
    name: 'green_theme/light/fill/product',
    color: 'c85200',
    styles: 'S:380f15d999c08d9d97725c9915f479e52c1a343c,244:13',
  },
  {
    name: 'green_theme/light/fill/active',
    color: '00880d',
    styles: 'S:b2aecc5927c659d7fba7d021b092bc90618043a5,189:0',
  },
  {
    name: 'green_theme/light/fill/product',
    color: '0081a0',
    styles: 'S:1f28c38bfa1b10ca61aeaf706ac2a71fa6425950,244:11',
  },
];

const newArr = arr.map(el => el.color === "eb40a2" ? {...el, color: "ffffff"}: el)

console.log(newArr)

【讨论】:

    猜你喜欢
    • 2018-09-02
    • 1970-01-01
    • 2023-01-19
    • 1970-01-01
    • 2017-05-11
    • 2018-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多