Reputation: 551
I have a javascript object which looks like
dict1 = {"key1":"value1",
"key2":"value2",
"key3":"value3",
"key4":"value4",
"key5":"value5"}
Next I have got an array which is arr1 = ["key1","key2"]
All I need to do is fetch the value from dict1 based elements in the array and concat them as string.
Sounds fairly Simple:
dict1[arr1[0]] + '-' + dict1[arr1[1]]
Output :
value1-value2
The tricky part for me is that the array arr1 can be of any length but is always the subset of keys present in dict1. For ex:
arr1= ["key2","key5"]
arr1= ["key1","key5","key3"]
arr1= ["key4"]
Based on these input following output is expected:
value2-value5
value1-value5-value3
value4
I am having trouble writing a generic script to create the string dynamically
Upvotes: 2
Views: 68
Reputation: 536
It's simple.
All you need to take a key at a time and get value from your dict
and then add that your main string.
Suppose:
let dict1 = {
"key1":"value1",
"key2":"value2",
"key3":"value3",
"key4":"value4",
"key5":"value5"
}
You can either use reduce or map.
reduce
way:
let genString = (subArray, obj) => subArray.reduce((acc, v, i) => [...acc, obj[v]] ,[]).join('-')
map
way:
let genString = (subArray, obj) => subArray.map((v, i) => obj[v]).join('-')
You can use like this:
genString(["key1","key5","key3"], dict1)
Upvotes: 1
Reputation: 5650
You can map over the keys you'd like to "pluck" the values from the object and concatenate all of those values together with join
.
const dict1 = {
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4",
"key5": "value5"
}
arr1 = ["key2", "key5"];
arr2 = ["key1", "key5", "key3"];
arr3 = ["key4"];
const pluckAndConcat = (obj, keys) => keys.map(key => obj[key]).join("-");
console.log(pluckAndConcat(dict1, arr1));
console.log(pluckAndConcat(dict1, arr2));
console.log(pluckAndConcat(dict1, arr3));
Upvotes: 3
Reputation: 33726
You can use the function reduce as follow:
let dict1 = {"key1":"value1","key2":"value2", "key3":"value3", "key4":"value4", "key5":"value5"};
let buildString = function(arr, obj) {
return arr.reduce((a, s) => a.concat(obj[s]), []).join("-")
};
console.log(buildString(["key2","key5"], dict1));
console.log(buildString(["key1","key5","key3"], dict1));
console.log(buildString(["key4"], dict1));
Upvotes: 1