如何迭代字符串中的键值对

时间:2017-09-29 17:24:15

标签: javascript

我有一个这样的字符串: var test =" oldsite1:newsite1,oldsite2:newsite2&#34 ;;

我想迭代这个来获取值。 我知道我可以像这样转换为字符串数组: var myArray = test.split(",");

然后我把整个字符串放到","我想提取" oldsite1"和" newsite1"。

帮助表示感谢。 感谢。

4 个答案:

答案 0 :(得分:1)

再次拆分每个数组项,并将键作为第一个元素,将值作为第二个

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]);
})

答案 1 :(得分:0)

我会使用split将字符串转换为数组,然后您可以使用数组方法进行操作。

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

答案 2 :(得分:0)

您的输入格式足够接近有效的JSON,我将在剩下的时间内使用它,然后使用JSON.parse将其转换为javascript对象。 (虽然如果你首先可以用JSON获取数据,那就更好了......)

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

答案 3 :(得分:0)

您可以合并split()map()将字符串转换为对象数组:

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);
})

相关问题