【问题标题】:Compare object with objects将对象与对象进行比较
【发布时间】:2018-04-09 09:37:56
【问题描述】:

我有那个带有简单对象的对象

public positions = {
    reading: {
        left: "0px",
    },
    writing: {
        left: "0px",
    },
    speaking: {
        left: "0px",
    },
    listening: {
        left: "0px",
    },
};

我需要检查一些“左”属性是否相同,以及是否将“顶部”属性添加到其中之一。例如,如果我有这样的对象:

public positions = {
    reading: {
        left: "10px",
    },
    writing: {
        left: "20px",
    },
    speaking: {
        left: "20px",
    },
    listening: {
        left: "7px",
    },
};

应该改成这样:

public positions = {
    reading: {
        left: "10px",
    },
    writing: {
        left: "20px",
    },
    speaking: {
        left: "20px",
        top: "10px"

    },
    listening: {
        left: "7px",
    },
};

我需要最简单的方法来做到这一点。

【问题讨论】:

  • public ?这是什么语言 - 所以你想将top: "10px" 添加到positions.speaking? ...喜欢:positions.speaking.top = '10px'
  • 您定义了优先级吗?哪个应该先出现?
  • 如果有多个具有相同值的此类键怎么办? top 值是否应该始终为 10px? left 是职位唯一可以拥有的属性吗?如果有多个公共属性怎么办?

标签: javascript object compare


【解决方案1】:

也许是这个?

const positions = {
    reading: {
        left: "0px",
    },
    writing: {
        left: "0px",
    },
    speaking: {
        left: "0px",
    },
    listening: {
        left: "0px",
    },
};

const positions2 = {
    reading: {
        left: "0px",
    },
    writing: {
        left: "0px",
    },
    speaking: {
        left: "0px",
    },
    listening: {
        left: "0px",
    },
};

for (var key in positions) {
  if (positions2[key].left == positions[key].left) {
    positions2[key].top = '10px'
  }
}

console.log(positions2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-01-21
    • 2022-09-30
    • 2015-07-17
    • 1970-01-01
    • 2012-01-26
    • 2018-04-06
    • 1970-01-01
    相关资源
    最近更新 更多