如何交换多个对象值?

时间:2017-04-06 11:24:51

标签: javascript

例如,我有两个具有相同键的对象:

var a = {
    k1: "aa", 
    k2: "ab", 
    k3: "ac", 
    k4: "ad",
    k5: "ae"        
}
var b = {
    k1: "ba", 
    k2: "bb", 
    k3: "bc", 
    k4: "bd",
    k5: "be"        
}

例如,我需要在这些对象之间交换值k2,k3,k4。所以,我想得到这个结果:

a = {
    k1: "aa", 
    k2: "bb", 
    k3: "bc", 
    k4: "bd",
    k5: "ae"        
}
b = {
    k1: "ba", 
    k2: "ab", 
    k3: "ac", 
    k4: "ad",
    k5: "be"        
}

有没有办法快速完成这项工作?我相信它可以在不添加中间对象的情况下执行。

2 个答案:

答案 0 :(得分:2)

使用Object.keys()Array.prototype.indexOf()函数的简单解决方案:



var a = {k1: "aa",k2: "ab",k3: "ac",k4: "ad",k5: "ae"},
    b = {k1: "ba",k2: "bb",k3: "bc",k4: "bd",k5: "be"},
    swapKeys = ['k2', 'k3', 'k4'];

swapKeys.forEach(function (k) {
    if (k in a && k in b) {
        var values = [a[k], b[k]];
        a[k] = values[1];
        b[k] = values[0];
    }
});

console.log(a);
console.log(b);




答案 1 :(得分:1)



shinyApp(
  ui = fluidPage(fluidRow(column(12, DT::dataTableOutput('tbl')))),
  server = function(input, output) {
    irisReact <- reactive(iris)
    dimIrisReact <- reactive(dim(iris)[1])    
    output$tbl = DT::renderDataTable(
      irisReact() %>% datatable() %>% formatStyle(
        0, target = "row",
        fontWeight = styleEqual(dimIrisReact(), "bold")
      )
    )
  }
)
&#13;
&#13;
&#13;

关于密钥和存储的全部内容。由于您的钥匙有一定的订单。 k1到k5,可以从对象var a = { k1: "aa", k2: "ab", k3: "ac", k4: "ad", k5: "ae" } var b = { k1: "ba", k2: "bb", k3: "bc", k4: "bd", k5: "be" } function swap(keys) { for (var i = 0; i < keys.length; i++) { var aOld = a["k"+keys[i]]; var bOld = b["k"+keys[i]]; a["k"+keys[i]] = bOld; b["k"+keys[i]] = aOld; } console.log(a); console.log(b); } swap([1,3,4]);a中相当容易地选择它们。如果循环键并存储值,您可以轻松地交换它们。