替换另一个变量中所述的属性名称

时间:2015-05-16 11:44:36

标签: javascript variables object

我不确定我应该如何表达它,但基本上我想实现这样的对象a

var a = {
"test123": "A",
"testing/test": "B",
"notest": "C"
};

和对象b

var b = {
"test123": "Test 123",
"testing": "Testing"
};

组合使得有一个对象c看起来像这样:

var c = {
"Test 123": "A",
"Testing/test": "B",
"notest": "C"
};

我希望你明白我在说什么。基本上将对象ab合并/替换为c,以便仅替换/之前的文本。

谢谢!

修改

万一你不明白,这就是我的意思。

在对象bb['test123'] = 'Test 123'中,a['test123']应变为c['Test 123'],因为它会根据b进行更改。

同样,自b['testing'] = 'Testing' a['testing/test']后,c['Testing/test']将变为b,如/中所述,只会Option Strict之后的文字不受影响。

2 个答案:

答案 0 :(得分:2)

var a = {
"test123": "A",
"testing/test": "B",
"notest": "C"
};

var b = {
"test123": "Test 123",
"testing": "Testing"
};

var c = {};
for (var p in a) {
  var prop = p.split("/")[0];

  if (b.hasOwnProperty(prop)) {
    c[p.replace(prop, b[prop])] = a[p];
  } else {
    c[p] = a[p];
  }
}
console.log(c);

http://plnkr.co/edit/Lhi5fLKkW4UBzhOK6le7?p=preview

答案 1 :(得分:1)

这应该这样做:

var a = {
  "test123": "A",
  "testing/test": "B",
  "notest": "C"
};


var b = {
  "test123": "Test 123",
  "testing": "Testing"
};

var c = {}

for (prop in a) {
    //console.log(prop);

    var propParts = prop.split("/");  // only get the first part of properties with an "/" in it

    if(b.hasOwnProperty(propParts[0])) {  // if we have a new property name in b, use that
        c[b[propParts[0]]] = a[prop];
    } else {     // if not, use the one that came from object a
        c[prop] = a[prop];
    }
}

console.log(c);

小提琴:http://jsfiddle.net/03ynxwa0/

修改

我错过了你也想要新属性名中的“/”。请参考yozh的回答!