我有一个数据对象如下:
[{"type":"Positive","value":14.71},{"type":"Neutral","value":50.0},{"type":"Negative","value":35.29}]
我想将其更改为以下指定的格式:
{
"refno": "",
"ddesc": "",
"free": "0",
"fgift": "",
"sgift": "",
"sandage": {
"bank": "",
"bag": ""
},
"inst": "",
"items": [{
"itemid": "606",
"qty": "1",
"sub": [{
"item": "1586",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1588",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1589",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1590",
"qty": "1",
"type": "addon",
"ext": ""
}]
}, {
"itemid": "639",
"qty": "1",
"sub": [{
"item": "1618",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1612",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1611",
"qty": "1",
"type": "addon",
"ext": ""
}, {
"item": "1610",
"qty": "1",
"type": "addon",
"ext": ""
}]
}],
"discount": "0",
"coupon": [],
"delivery": "",
"user": {
"id": "13",
"fname": "Demo",
"lname": "Order",
"phone": "9876543210",
"dno": "",
"add1": "",
"add2": "",
"postcode": "",
"username": "demo@theepos.com",
"status": "1"
},
"otype": "1",
"ptype": "0",
"app_id": "A1A2A3A4",
"app_key": "K1K2K3K4",
"request": "placeorder"
}
答案 0 :(得分:5)
使用 Object.keys
和 Array#map
方法。
var data = [{
"Positive": "14.71",
"Neutral": "50.0",
"Negative": "35.29"
}];
var res = Object.keys(data[0]) // get all object property names
// iterate over property names array
.map(function(k) {
// generate array element using property value
return {
type: k,
// cast data value to number using plus-sign prefix(as per requirement)
value: +data[0][k]
}
})
console.log(res);

答案 1 :(得分:2)
我使用通用的has no exported mng 'provideRouter'
has no exported mng 'RouterConfig'
has no exported mng 'ROUTER_DIRECTIVES'
has no exported mng 'addProviders'
函数解决了这个问题,这对您在JavaScript中尝试pairs
,map
或reduce
个对象非常有用
filter
或者,let input = [{"Positive":"14.71","Neutral":"50.0","Negative":"35.29"}];
let pairs = o =>
Object.keys(o).reduce((acc,k) => [...acc, [k, o[k]]], []);
let output = pairs(input[0]).map(([type,value]) =>
({type, value: Number(value)}));
console.log(output);
可以作为生成器实现,这将产生整体更可读的结果
pairs
let input = [{"Positive":"14.71","Neutral":"50.0","Negative":"35.29"}];
function* pairs(o) {
for (let k of Object.keys(o))
yield [k, o[k]];
}
let output = Array.from(pairs(input[0]), ([type, value]) => {
return {type, value: Number(value)};
});
console.log(output);
提供了一种从可迭代值(以及可选 map )中收集值的便捷方法,但您不必使用它,如果你不想。在熟悉它之前,您可以轻松地使用Array.from
循环将键/值对收集到输出对象中。
for-of