如何在嵌套在另一个对象数组中的对象数组中连接字符串?

时间:2017-11-15 01:56:59

标签: javascript

这是我正在使用的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;
}

3 个答案:

答案 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

&#13;
&#13;
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;
&#13;
&#13;

答案 2 :(得分:0)

我会结合使用javascript的reducemap函数

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的数学,所以如果有人可以证明我错了,请告诉我!