Home > Blockchain >  How to create an object from an array of strings with string splits?
How to create an object from an array of strings with string splits?

Time:08-10

I have an array of strings. I need to create an object in which the keys are the values from the strings to the left of the = symbol, and their values are the text in the string to the right of the = symbol in the string. Can you please tell me how to implement this?

    const testArray = ["test1=25", "test2=1", "test3=2015-01-02" ]
    
    
     const testObjects = ??? 

     // i want to get similar object
      {
        test1: "25",
        test2: "1",
        test3 : "2015-01-02",
      }

CodePudding user response:

You can use Object.fromEntries() apprach along with .map to prepare entries:

 const testArray = ["test1=25", "test2=1", "test3=2015-01-02" ]
 
 const entries = testArray.map(e => e.split('='));
 
 const result = Object.fromEntries(entries);
 
 console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0 }

CodePudding user response:

I'm sure there are more optimized ways of doing this, however this does get you the result you want. Please be aware there is no validation here, meaning if an item in your array is missing the equals sign "=" (or any delimeter you want to use), it will fail.

const testArray = ["test1=25", "test2=1", "test3=2015-01-02" ];
let testObj = {};

testArray.forEach(item => {
    testObj[item.split("=")[0]] = item.split("=")[1];
});

console.log(testObj);

CodePudding user response:

 const testArray = ["test1=25", "test2=1", "test3=2015-01-02" ]
 let t = testArray.map((e)=>e.split('='));
 
 const obj = {};
 for (const key of t) {
      obj[key[0]] = key[1];
 }

console.log ( 'obj : ',obj);

  • Related