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
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: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.Just going through all of the obj keys and when I find a match I replace that idx with obj value for that key