开发者

Realiable mergin two JavaScript objects and altering their key names

开发者 https://www.devze.com 2023-03-24 05:44 出处:网络
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, wh

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, bu开发者_StackOverflow中文版t it feels ugly, and I'm wondering if there's a better way.


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消