简体   繁体   中英

How to Iterate key value pairs in a string

I have a string like this: var test = "oldsite1: newsite1, oldsite2: newsite2";

I want to iterate over this to get the values. I know I can convert to a string array like this: var myArray = test.split(",");

but then I get the whole of the string up to the "," and I want to extract "oldsite1" and "newsite1".

Help appreciated. Thanks.

Split again each array item and get the key as the first element and the value as the second

 var test = "oldsite1: newsite1, oldsite2: newsite2"; var items= test.split(','); items.forEach(function(item) { var keyValue = item.split(":") console.log("this is the key: " + keyValue[0]); console.log("this is the value: " + keyValue[1]); })

I would use split to convert the string to an array and then you can use array methods to manipulate.

 var test = "oldsite1: newsite1, oldsite2: newsite2"; var split = test.split(','); split.forEach(function(item) { console.log(item); }) console.log(split) //outputs an array of key values

Your input format is close enough to valid JSON that I'd take it the rest of the way and then use JSON.parse to turn it into a javascript object. (Though if you can have your data in JSON in the first place, that'd be preferable...)

 var test = "oldsite1: newsite1, oldsite2: newsite2" // wrap field names in quotes, and put curlies around the whole thing: test = '{"'+ test.replace(/([:,]) /g, '"$1 "') + '"}'; var obj = JSON.parse(test); // Now you can use obj as a regular old hash table: console.log("All keys are ", Object.keys(obj)); console.log("oldsite1's value is ", obj.oldsite1); // and so on

You may combine split() and map() to convert your string into an array of objects:

 var test = "oldsite1: newsite1, oldsite2: newsite2"; testArr = test.split(',').map(function(ele, idx){ var arr = ele.split(':'); var retVal = {}; retVal[arr[0]] = arr[1].trim(); return retVal; }); console.log(testArr); testArr.forEach(function(ele, idx) { var keyName = Object.keys(ele)[0]; var keyValue = ele[keyName]; console.log('keyName: ' + keyName + ' keyValue: ' + keyValue); })

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