lodash找到键值并用JSON中的变量替换

时间:2016-03-21 08:58:12

标签: javascript lodash

我想用我的变量替换selectedCIID的值。 我可以使用JS for循环来进行itreting。

但我想用lodash来获得有效的结果。

JSON:

{
    "rows": [{
        "title": " row 1",
        "panels": [{
            "targets": [{
                "selectedCIID": "5856742957ce424b8db6cfb309b6b013",
                "series": ""
            }]
        }]
    }, {
        "title": "row 2",
        "panels": [{
            "targets": [{
                "selectedCIID": "5856742957ce424b8db6cfb309b6b013",
                "series": ""
            }]
        }, {
            "targets": [{
                "selectedCIID": "5856742957ce424b8db6cfb309b6b013",
                "series": ""
            }]
        }]
    }]
}

请帮忙。

3 个答案:

答案 0 :(得分:0)

使用普通的javascript,您可以在没有lodash的情况下有效地解决问题

var json = { "rows": [{ "title": " row 1", "panels": [{ "targets": [{ "selectedCIID": "5856742957ce424b8db6cfb309b6b013", "series": "" }] }] }, { "title": "row 2", "panels": [{ "targets": [{ "selectedCIID": "5856742957ce424b8db6cfb309b6b013", "series": "" }] }, { "targets": [{ "selectedCIID": "5856742957ce424b8db6cfb309b6b013", "series": "" }] }] }] };
var newValue = "55555";

json.rows.forEach(a => a.panels.forEach(
    b => b.targets.forEach(c => c.selectedCIID = newValue)));

document.write('<pre>' + JSON.stringify(json, 0, 2)+ '</pre>');

答案 1 :(得分:0)

由于json的结构复杂,它不是很短。

var data = {
  "rows": [{
    "title": " row 1",
    "panels": [{
      "targets": [{
        "selectedCIID": "5856742957ce424b8db6cfb309b6b013",
        "series": ""
      }]
    }]
  }, {
    "title": "row 2",
    "panels": [{
      "targets": [{
        "selectedCIID": "5856742957ce424b8db6cfb309b6b013",
        "series": ""
      }]
    }, {
      "targets": [{
        "selectedCIID": "5856742957ce424b8db6cfb309b6b013",
        "series": ""
      }]
    }]
  }]
}

var transformedData = _.each(data.rows, function(row) {
  _.each(row.panels, function(panel) {
    _.each(panel.targets, function(target) {
      target.selectedCIID = 'new value';
    });
  });
});

console.log(transformedData);

这是jsfiddle

答案 2 :(得分:0)

我用_.forIn和它为我工作。

var dashboard = results.dashboard;
          var dashboardJson = angular.fromJson(dashboard);
          if(ciid.length > 1) {
            _.forIn(dashboardJson.rows, function(value0) {
              _.forIn(value0.panels, function(value1) {
                _.forIn(value1.targets, function(value2) {
                  value2.selectedCIID = ciid;
                });
              });
            });
          }