重组javascript对象中的对象

时间:2018-11-22 13:50:32

标签: javascript object

我有一个object,例如“模型”:

var model = {
    comments: {
        123: "I disagree on this",
        42563: "Sounds correct"
    },
    answer: {
        123: "No",
        87: "Yes"
    }
};

我需要将“模型” object重构为:

var wishModel = {
    123: {
        answer: "No",
        comments: "I disagree on this"
    },
    87: {
        answer: "Yes"
    },
    42563: {
        comments: "Sounds correct"
    }
};

我在使用JavaScript objects方面是一个新手,并且不知道从哪里开始。

2 个答案:

答案 0 :(得分:-1)

这是一种符合新手的方式:

var wishModel = {};

for (var key of ["comments", "answer"]) {
  for (var prop in model[key]) {
    wishModel[prop] = wishModel[prop] || {};
    wishModel[prop][key] = model[key][prop];
  }
}

答案 1 :(得分:-1)

您可以像下面一样使用<script type="text/javascript"> if (screen.width <= 720) { window.location = "indexm.php"; } else { window.location = "index.php"; } </script> 遍历对象

for..of