我有这个数组:
[{abcd:1, cdef:7},{abcd:2, cdef:8}, {abcd:3, cdef:9}]
我想将其中的所有值格式化为这样的字符串:
[{abcd:"1", cdef:"7"},{abcd:"2", cdef:"8"}, {abcd:"3", cdef:"9"}]
请帮助
答案 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;
})