Reputation: 31
Here's the JSON object I'm working with:
var object = {
"units": [
{ "unitNum": "1", "fuels": [{ "fuelDesc": "Coal" }] },
{ "unitNum": "2", "fuels": [{ "fuelDesc": "Pipeline Natural Gas" }] }
]
}
What's the most performative way of concatenating all of the fuelDesc
strings into one string, separated by ,
?
NOTE: I've simplified the object here. The actual objects is a lot larger so I'm concerned with performance. Also, the fuels array can have more than one item.
The result would be "Coal,Pipeline Natural Gas".
I did this:
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;
}
Upvotes: 0
Views: 831
Reputation: 372
i would use a combination of javascript's reduce and map functions
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);
I believe this is just about as efficient as you can get, but its been a while since ive done math involving big O so if someone can prove me wrong let me know!
Upvotes: 0
Reputation: 22876
For JSON string, the JSON.parse
reviver can be used:
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 + '')
For JavaScript object, the 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 + '')
Upvotes: 2
Reputation: 222582
Based on assumption that you always have one element inside the fuels array. you can use .map
and .join
together
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);
Upvotes: 1