简体   繁体   中英

Javascript how to create key:values from a string

I have an array of strings in the form of key:values separated by " :: " and the values can have multiple lines. I'd like to know how could I create a hashtable matching the keys to specific strings and map the values and build a JSON file from it? Sorry if it has been answered already but I've been searching all day and couldn't find a way to achieve that. Thanks, Didi

I din't really get what you want exactly. But from what I understood, this should be what you want. Could you provide some snippets ?

var myObject = {
pro1 : "value1",
prop2: "value2"
}
JSON.stringify(myObject);  // outputs the object as json

Something like

var stringsArray=['key1::value1','key2::value2','key3::value3'.....]
var hashObj={};

for(var i=0; i<stringsArray.length; i++){
    var kv=stringsArray[i].split('::')
    hashObj[kv[0]]=kv[1];
}

alert(hashObj.key1)

This will only work for unique key values

For example strings = ["a::1", "b::2", "c::3"]. What you can do is.

let output = {};
for (let i = 0; i < strings.length; ++i)
{
    let key = strings[i].split("::")[0];
    let value = strings[i].split("::")[1];
    output[key] = value;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM