这是我正在使用的JSON对象:
var object = {
"units": [
{ "unitNum": "1", "fuels": [{ "fuelDesc": "Coal" }] },
{ "unitNum": "2", "fuels": [{ "fuelDesc": "Pipeline Natural Gas" }] }
]
}
将所有fuelDesc
个字符串连接成一个字符串,以,
分隔的最具表现力的方法是什么?
注意:我在这里简化了对象。实际的对象要大得多,所以我关心的是性能。此外,燃料阵列可以有多个项目。
结果将是“煤炭,管道天然气”。
我这样做了:
var fuelsStr = "";
for (i = 0; i < units.length; i += 1) {
var mergedFuels = [].concat.apply([], units[i].fuels)
var unitFuelStr = mergedFuels.map(function (mergedFuels) {
return mergedFuels["fuelDesc"];
}).join(",");
fuelsStr += unitFuelStr;
}
答案 0 :(得分:2)
对于JSON字符串,可以使用JSON.parse
reviver:
a = [], j = '{"units":[{"unitNum":"1","fuels":[{"fuelDesc":"Coal"}]},{"unitNum":"2","fuels":[{"fuelDesc":"Pipeline Natural Gas"}]}]}'
JSON.parse(j, (k, v) => k === "fuelDesc" ? a.push(v) : 0)
console.log(a + '')
对于JavaScript对象,JSON.stringify
replacer:
a = [], o = {"units":[{"unitNum":"1","fuels":[{"fuelDesc":"Coal"}]},{"unitNum":"2","fuels":[{"fuelDesc":"Pipeline Natural Gas"}]}]}
JSON.stringify(o, (k, v) => k === "fuelDesc" ? a.push(v) : v)
console.log(a + '')
答案 1 :(得分:1)
基于假设您在燃料数组中始终有一个元素。您可以一起使用 .map
和 .join
var myobject = {"units":[{"unitNum": "1","fuels":[{"fuelDesc":"Coal"}]},
{"unitNum": "2","fuels":[{"fuelDesc":"Pipeline Natural Gas"}]}]};
var result = myobject.units.map(function(elem){
return elem.fuels[0].fuelDesc;
}).join(",");
console.log(result);
&#13;
答案 2 :(得分:0)
var object = {
"units": [{
"unitNum": "1",
"fuels": [{
"fuelDesc": "Coal"
}]
}, {
"unitNum": "2",
"fuels": [{
"fuelDesc": "Pipeline Natural Gas"
}, {
"fuelDesc": "some fuel"
}]
}]
};
var myStr = object.units.reduce(
(first, second) =>
first.fuels.map(item =>
item.fuelDesc)
.concat(second.fuels.map(item => item.fuelDesc))).join()
console.log(myStr);
我相信这和你能得到的效率差不多,但是因为我已经完成了涉及大O的数学,所以如果有人可以证明我错了,请告诉我!