skip to Main Content

I want to exactly match the key from an Object to an element in an array and replace the match in the array with the key value.

I have

Arr = [ 'Saturday', 'niCCCght', 'plans,', 'CCC' ]

Obj = { "AAA": "BBB", "CCC": "DDD", "EEE": "FFF" }

with below I get

[ 
  [ 'Saturday', 'Saturday', 'Saturday' ],
  [ 'niCCCght', 'niCCCght', 'niCCCght' ],
  [ 'plans,', 'plans,', 'plans,' ],
  [ 'CCC', 'DDD', 'CCC' ] 
]

I want

[ 'Saturday', 'niCCCght', 'plans,', 'DDD' ]

Thank you

function test() {
  let Arr = [ 'Saturday', 'niCCCght', 'plans,', 'CCC' ];

  const Obj = {"AAA":"BBB", "CCC":"DDD","EEE":"FFF"};
  
  const Z = Arr.map(v => matchedKey(Obj,v))

  console.log(Z);
}
let matchedKey = (Obj,str) => Object.keys(Obj).map(key => key===str ? Obj[key]: str);

2

Answers


  1. Your implementation is a lot more complicated than it needs to be. Simply map() over the input array and search for a matching property name in the object. If one is found, return that property value otherwise the original value:

    const arr = ['Saturday', 'niCCCght', 'plans,', 'CCC']
    const obj = { "AAA": "BBB", "CCC": "DDD", "EEE": "FFF" }
    
    var output = arr.map(v => obj[v] ?? v);
    console.log(output);

    Alternatively you can use hasOwnProperty() which is a little more descriptive in outlining what the logic is doing. The output of both will be the same, though.

    var output = arr.map(v => obj.hasOwnProperty(v) ? obj[v] : v);
    
    Login or Signup to reply.
  2. Just going through all of the obj keys and when I find a match I replace that idx with obj value for that key

    function test() {
      var arr = ['Saturday', 'niCCCght', 'plans,', 'CCC'];
      const obj = { "AAA": "BBB", "CCC": "DDD", "EEE": "FFF" };
      Object.keys(obj).forEach(k => {
        let idx = arr.indexOf(k)
        if (~idx) arr[idx] = obj[k];
      })
      Logger.log(JSON.stringify(arr))
    }
    
    Execution log
    1:24:36 PM  Notice  Execution started
    1:24:30 PM  Info    ["Saturday","niCCCght","plans,","DDD"]
    1:24:38 PM  Notice  Execution completed
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search