0

This is not so much a question as a request for comments.

I have two objects, and I want to merge them together, taking the values of the second, and merging with (overwriting) those of the first, while keeping the property names of the first.

The key names in the second object are long and descriptive for human consumption, whereas the key names of the first are terse and ugly to save bytes.

I was using jQuery, before readability of the second object became a concern, so now I've tossed together my own way of doing this. However, since iterating over objects doesn't return their key/value pairs in their original order, I'm wondering if this is a viable solution long term. Hopefully the code explains this better.

Ideas please and thanks in advance! :)

var ob = {}, i = 0, k, pArr = [];

for( k in p ){

    if( p.hasOwnProperty(k) ){
        pArr.push(k);
    }

}

for( k in c ){

    if( c.hasOwnProperty(k) ){
        ob[pArr[i]] = c[k];
    }

    i++;

}

The ob object now has all the properties from the second object, but with the key names of the first. This does work, but it feels ugly, and I'm wondering if there's a better way.

Tom
  • 2,792
  • 2
  • 14
  • 12

1 Answers1

0

You already have discovered that the loop does not return the objects in any particular order. The line ob[pArr[i]] = cArr[k]; is therefore not safe.

  1. You will need a mapping of the key names (lets say p_key => c_key).

  2. Iterate over the mapping.

Example:

for (p_key in map)
    c_key = map[p_key];
    ob[p_key] = c[c_key];

Example2 - Keeping the genuine p properties:

for (p_key in p) ob[p_key] = p[p_key];
for (... same as above)
Kaken Bok
  • 3,385
  • 1
  • 17
  • 21
  • That allows me to overwrite an object with a second object, value per value, but doesn't allow me to keep the property names of the first object, too. But I'm tweaking it. – Tom Jul 30 '11 at 23:51
  • Well, then simply change `ob[p_key] = c[c_key]` to `p[p_key] = c[c_key]` and your first object is updated with all the values of the second one. But if you want all not mapped p-keys, you need to init `ob` with all the values of `p` beforehand. – Kaken Bok Jul 30 '11 at 23:54
  • Using my method, repeating the process 100000 times, all properties turn out the same on the way out as they did on the way in... Is this just chance? – Tom Jul 31 '11 at 00:15
  • In your second example it keeps the key names from the first object, but also the property values... – Tom Jul 31 '11 at 00:16
  • You run example2 and then example1 (... same as above). Regarding the order: http://stackoverflow.com/questions/280713/elements-order-for-in-loop-in-javascript – Kaken Bok Jul 31 '11 at 00:31