2

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

1
  • 2
    arr1.map(key=>dict1[key]).join("-")? Commented May 7, 2020 at 15:21

3 Answers 3

3

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));

Sign up to request clarification or add additional context in comments.

Comments

1

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));

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.