Search code examples
javascriptarraysdictionaryecmascript-5

two object search by key and swap value


I want to replace objectB key from objectA value. and before that swap,objectA and ObjectB key should be matching in each object. then return data in objectC.

i saw this thread, but i just want matching key before swapping key and value. Swap key with value JSON

like this

 var objA ={100:'new',200:'in progress',300:'done',500:'exception',225:'critical'};

 var objB ={100:12,200:5,300:50};

objectA and objectB are having same key.

objectA key is statusID,and value is like Display statusID name for user.

objectB key is statusID,and value is statusID count.so this count value is sample.

so first,I want objectA and objectB key matching.this time, 100,200,300 are same keys.

and if they are matching,matched objectA key's value replacing objectB key. like, key 100 is matched,objectB key 100 should turn to 'new'. then finally,objectC result should be like this.

var objC ={'new':12,'in progress':5,'done':50};

any suggestion are welcome. thanks for read.


Solution

  • heck, i don't know what you're doing -

    const heck = (a = {}, b = {}) =>
      Object
        .entries(a)                   // using all entries from either object ...
        .reduce                       // reduce each ...
          ( (r, [ k, v ]) =>          // result, r, and key/value pair
              b[k] === undefined      // if key does not exist in other object
                ? r                   // continue with current result
                : { ...r, [v]: b[k] } // otherwise extend result with new key/value
          , {}                        // initial result
          )
    
    const objA =
      {100:'new', 200:'in progress', 300:'done', 500:'exception', 225:'critical'}
    
    const objB =
      {100:12, 200:5, 300:50}
    
    console.log(heck(objA, objB))
    
    // { "new": 12
    // , "in progress": 5
    // , "done": 50
    // }

    Here's another way to write it that's possibly easier to understand. The down-side is that it does a bit of unnecessary iteration -

    const heck = (a = {}, b = {}) =>
      Object.fromEntries                     // create new object from ...
        ( Object
            .keys(a)                         // all keys of either object
            .filter(k => b[k] !== undefined) // filter out non-matches in other
            .map(k => [ a[k], b[k] ])        // new [key, value] pair
        )