将字符串数组转换为键值对

时间:2019-05-02 12:44:53

标签: javascript foreach array.prototype.map

我有一个来自后端源的字符串,格式为:

数字:“ 1123763449056714753、1123764853364097024、1123770213739241473 ...”

我想将其转换为某种形式的键-值对,以便可以为我的个人项目div映射这些ID:

["numbers": [ 
              {"id":1123763449056714753 }, 
              {"id":1123764853364097024 },
              {"id":1123770213739241473 },
             ....
            ]
]

[                 {"id":1123763449056714753 }, 
                  {"id":1123764853364097024 },
                  {"id":1123770213739241473 },
                 ....

    ]

我尝试使用forEach()/ map(),但由于未定义而出错。我也不确定是字符串的集合还是字符串的数组 请帮助

6 个答案:

答案 0 :(得分:2)

您可以通过保留字符串(大于允许的整数值)来分割字符串并映射对象。

var object = { numbers: "1123763449056714753,1123764853364097024,1123770213739241473,1123771975162368003" },
    numbers = object.numbers.split(',').map(id => ({ id }));

console.log(numbers);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:1)

您可以做的一件事就是将数字作为数组:

var obj = {
  "numbers": "1123763449056714753,1123764853364097024,1123770213739241473,1123771975162368003"
};

var result = obj.numbers.split(',').reduce((acc, num) => {
  acc.push({ id: num });
  return acc;
}, []);

console.log(result)

或@briosheje提到,您也可以使用map

var result = obj.numbers.split(',').map(num => ({id: num}));

结果如下:

[{"id":"1123763449056714753"},{"id":"1123764853364097024"},{"id":"1123770213739241473"},{"id":"1123771975162368003"}]

答案 2 :(得分:1)

var arr = ["1123763449056714753","1123764853364097024","1123770213739241473","1123771975162368003"];
var newArr = [];
for (var i = 0; i < arr.length; i++) {
    var obj = {};
    obj.id = arr[i];
    newArr.push(obj);
}
console.log(newArr)

答案 3 :(得分:1)

您可以执行以下操作。

var data = {"numbers":"1123763449056714753,1123764853364097024,1123770213739241473,1123771975162368003"};

data.numbers = data.numbers.split(',').reduce((res, id) => [...res, {id}], []);

答案 4 :(得分:1)

您可以先split对象,再map它并返回所需的结构:

const obj = {
  "numbers": "1123763449056714753,1123764853364097024,1123770213739241473,1123771975162368003..."
}


const res = {
  numbers: [
    obj.numbers.split(",").map(el => ({
      id: el
    }))
  ]
}

console.log(res);

答案 5 :(得分:0)

根据您的数据,您可以使用“,”分割数字字符串,然后循环遍历以执行转换,例如

var data = {"numbers":"1123763449056714753,1123764853364097024,1123770213739241473,1123771975162368003"};
var numbers_arr = data.numbers.split(",");
var result = {
  "numbers":[]
};
for(var i=0;i<numbers_arr.length;i++){
 var tempObj = {
    "id":parseInt(numbers_arr[i])
  };
  result.numbers.push(tempObj)
}

console.log(JSON.stringify(result));