在数组对象中操作数据

时间:2019-02-21 07:24:09

标签: javascript object

我想遍历一个对象并对数据进行一些更改。如果im实际处理的是一个对象或包含多个对象的数组,则不是100%,因此不胜感激。

这是我的对象:

var screening = {
    source: "jacket",
    value: {
        Cyan: {
            dotshape: "C",
            frequency: 120,
            angle: 67.5
        },
        Magenta: {
            dotshape: "C",
            frequency: 120,
            angle: 37.5
        },
        Yellow: {
            dotshape: "C",
            frequency: 120,
            angle: 82.5
        },
        "PANTONE 3528 C": {
            dotshape: "C",
            frequency: 120,
            angle: 7.5
        },
        "PANTONE 293 C": {
            dotshape: "C",
            frequency: 120,
            angle: 7.5
        },
        "PANTONE 2748 C": {
            dotshape: "C",
            frequency: 120,
            angle: 7.5
        },
        Varnish: {
            dotshape: "C",
            frequency: 120,
            angle: 0
        }
    }
}

在内部,我实际上想根据2个列表查找并替换“键”(同样不确定术语)。

Old = [Cyan, Magenta, Yellow]
new = [changedName1, changedName2, changedName3]

理想情况下,我希望循环查看当前对象,如果它与数组Old中的某项匹配,则根据New重命名它。如果与Old数组中的某项不匹配,则忽略它并保持原样。

预先感谢

1 个答案:

答案 0 :(得分:0)

使用delete删除旧属性,并使用[](方括号表示法)和indexOf获取旧属性并创建新属性:

var screening = {
  source: "jacket",
  value: {
    Cyan: {
      dotshape: "C",
      frequency: 120,
      angle: 67.5
    },
    Magenta: {
      dotshape: "C",
      frequency: 120,
      angle: 37.5
    },
    Yellow: {
      dotshape: "C",
      frequency: 120,
      angle: 82.5
    },
    "PANTONE 3528 C": {
      dotshape: "C",
      frequency: 120,
      angle: 7.5
    },
    "PANTONE 293 C": {
      dotshape: "C",
      frequency: 120,
      angle: 7.5
    },
    "PANTONE 2748 C": {
      dotshape: "C",
      frequency: 120,
      angle: 7.5
    },
    Varnish: {
      dotshape: "C",
      frequency: 120,
      angle: 0
    }
  }
};

function oldToNew(oldNames, newNames) {
  Object.entries(screening.value).forEach(([key, prop]) => {
    if (oldNames.includes(key)) {
      screening.value[newNames[oldNames.indexOf(key)]] = screening.value[key];
      delete screening.value[key];
    }
  });
}

oldToNew(["Cyan", "Magenta", "Yellow"], ["Blue", "Purple", "Orange"]);

console.log(screening.value);

注意:属性将不按顺序排列,因为如ECMAScript Specification所示:

  

ECMAScript 对象是{strong>属性

unordered集合