I have an array like below:
["gender-m", "age-20", "city-london", "lang-en", "support-home"]
I tried to generate a JSON object:
{"gender":"m", "age":"20", "city":"london", "lang":"en", "support":"home"}
One solution I can think of is using FOR loop to make it, but I am sure there are elegant solutions for this. Any suggestions, please help me.
Splitting the Array Into Even Chunks Using slice() Method The easiest way to extract a chunk of an array, or rather, to slice it up, is the slice() method: slice(start, end) - Returns a part of the invoked array, between the start and end indices.
The split() method splits (divides) a string into two or more substrings depending on a splitter (or divider). The splitter can be a single character, another string, or a regular expression. After splitting the string into multiple substrings, the split() method puts them in an array and returns it.
String splitting is the process of breaking up a text string in a systematic way so that the individual parts of the text can be processed. For example, a timestamp could be broken up into hours, minutes, and seconds so that those values can be used in the numeric analysis.
We'll go over each of those methods in this article and provide some code examples for you to use on your website or application. Let's get started! 1. Object.assign () Object.assign () is the first method we'll cover for converting an array to an object. This method is used to copy values from one or more source objects to a new object.
Table of Contents 1 Object.assign () Object.assign () is the first method we'll cover for converting an array to an object. ... 2 Loop Over Array & Construct a New Object For the second method, we're going to loop over each item in an array and add each of its values as ... 3 Reduce ()
We can convert an Object {} to an Array [] of key-value pairs using methods discussed below: Method 1: In this method, we will use Object.keys () and map () to achieve this. Approach: By using Object.keys (), we are extracting keys from the Object then this key passed to map () function which maps the key and corresponding value as an array, ...
For display it, JSON.stringify () method is used. | Convert Array to Object. Example-2: This example converts the array to object by creating a function which adds the array values one by one to the object. For display it, JSON.stringify () method is used.
You could take Object.fromEntries
with the splitted key/value pairs.
var data = ["gender-m", "age-20", "city-london", "lang-en", "support-home"],
result = Object.fromEntries(data.map(s => s.split('-')));
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With