Reputation:
I'm not exactly sure how I should phrase it but basically I want to achieve such that object a
:
var a = {
"test123": "A",
"testing/test": "B",
"notest": "C"
};
and object b
:
var b = {
"test123": "Test 123",
"testing": "Testing"
};
combine such that there is an object c
that looks like this:
var c = {
"Test 123": "A",
"Testing/test": "B",
"notest": "C"
};
I hope you understand what I'm talking about. Basically combine / replace objects a
and b
into a c
such that only the text before /
is replaced.
Thanks!
EDIT:
Just in case you don't get it, this is what I mean.
In object b
, b['test123'] = 'Test 123'
so that a['test123']
should turn into c['Test 123']
because it is changed based on b
.
Also since b['testing'] = 'Testing'
, a['testing/test']
would turn into c['Testing/test']
as stated in b
, just that the text after the /
is not affected.
Upvotes: 2
Views: 53
Reputation: 6953
This should do it:
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);
Fiddle: http://jsfiddle.net/03ynxwa0/
EDIT:
I missed that you also want the "/" in the new propertyname. Please refer to yozh's answer!
Upvotes: 1
Reputation: 1223
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
Upvotes: 2