-1

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.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
idotassadar
  • 35
  • 1
  • 5

2 Answers2

0

You should think of this as creating a new object that combines data from the other two objects. You can do what you want by calling reduce() on the array of keys in objB:

objC = objB.keys().reduce(result, key => {
    result[objA[key]] = objC[key];
    return result;
});
Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
  • naively assigns `result[objA[key]]` where `objA[key]` is possibly `undefined` – Mulan Oct 09 '19 at 16:26
  • @user633183 Yes, I wrote this based on some assumptions from the OPs example dictionaries. More robust code will check for `undefined` values. – Code-Apprentice Oct 09 '19 at 16:46
0

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
    )
Mulan
  • 129,518
  • 31
  • 228
  • 259