How i can assign the nc key value to nc variable which i have declared.
const s = [
'nc: https://nector.com',
'tw: https://twitter.com; li: https://www.linkedin.com; fb: https://www.facebook.com'
]
var li = '';
var tw = '';
var fb = '';
var nc = "";
s.forEach((items) => {
const a = items.split(" ")
const search = query => a.filter(str => str.includes(query))
li = search("linkedin")
tw = search("twitter")
fb = search("facebook")
})
})
I have tried doing it with matching the char in the string able to do it but looking for solution so it can be done on the basis of key.
Note: Array elements are little weird.
3
Answers
This code extracts all key-value pairs as an array, then constructs an object from the result. Finally, we destructure to extract object properties into variables.
You can use reduce method to do this. The steps would be the following-
s
array using reduce and spit the item by;
.:
and assign it into a key-value pair.Here is the demo-
You can modify your code to assign the nc key value to the nc variable like this:
Here’s what has been changed:
Updated the search query for each variable to include the colon (e.g., li: instead of linkedin).
After the forEach loop, added code to remove the prefixes and keep only the URLs for each variable.
Now the nc variable will be assigned the value corresponding to the nc key from the input array s.