将数组中的元素从数字转换为字符串

时间:2017-12-15 15:33:32

标签: javascript arrays string formatting

我有这个数组:

[{abcd:1, cdef:7},{abcd:2, cdef:8}, {abcd:3, cdef:9}]

我想将其中的所有值格式化为这样的字符串:

[{abcd:"1", cdef:"7"},{abcd:"2", cdef:"8"}, {abcd:"3", cdef:"9"}]

请帮助

3 个答案:

答案 0 :(得分:0)

let aItems = [{abcd:1, cdef:7},{abcd:2, cdef:8}, {abcd:3, cdef:9}];

aItems.forEach(oItem => {
    for(let sKey in oItem) {
        if(oItem.hasOwnProperty(sKey)) {
            oItem[sKey] = '' + oItem[sKey];
        }
    }
});

答案 1 :(得分:0)

您可以将.map()Object.entries()一起使用,并在对象文字中传播语法。 String函数会为您转换值。



var data = [{abcd:1, cdef:7},{abcd:2, cdef:8}, {abcd:3, cdef:9}];

var result = data.map(o =>
  ({...Object.entries(o).map(([k,v]) => ({[k]:String(v)}))})
);

console.log(result);




或者如果你想改变原作:



var data = [{abcd:1, cdef:7},{abcd:2, cdef:8}, {abcd:3, cdef:9}];

for (const o of data) {
  for (const [k,v] of Object.entries(o)) o[k] = String(v);
}

console.log(data);




或使用Object.assign



var data = [{abcd:1, cdef:7},{abcd:2, cdef:8}, {abcd:3, cdef:9}];

for (const o of data) {
  Object.assign(o, ...Object.entries(o).map(([k,v])=>({[k]:String(v)})));
}

console.log(data);




答案 2 :(得分:0)

映射数组并在将每个键值对转换为字符串后将其分配给新对象。

const array = [{abcd:1, cdef:7},{abcd:2, cdef:8}, {abcd:3, cdef:9}];

array.map(el => {
  const stringObj = {}
  Object.keys(el).forEach(key => {
    stringObj[key] = el[key].toString();
  })
  return stringObj;
})