从数组中添加json密钥

时间:2018-04-09 10:54:06

标签: javascript jquery arrays json dictionary

我正在尝试从数组项中向JSON添加元素,但我很难将元素传递给JSON。

这是我的代码:

var j = {
    "Root": {
        "a": "1800,1200,3100",
        "b": "1500,1999,2001",
        "c": "40,60,50",
        "d": "this is not needed",
        "e": "nor this one"
    }
};
var root = j.Root,
    l = root.a.split(",").length,
    hash = ["a", "b", "c"];


for (var i = 0; i < l; i++) {
    for (var x = 0; x < hash.length; x++) {
        root['row_' + i] = {
            "a": root.a.split(",")[i],
            "b": root.b.split(",")[i],
            "c": root.c.split(",")[i] // I don't want to do this for each key
        };
    }
}



for (var x = 0; x < hash.length; x++) {
    delete root[hash[x]];
}

console.log(JSON.stringify(j));

我的代码正在运行,但我正在寻找一种正确的方法来使用我的数组元素,因为我将拥有多个,b,c

PS:并非所有密钥都将被使用

3 个答案:

答案 0 :(得分:1)

您可以使用Object.keys来为hash变量中的对象提供密钥。然后,代码将动态检测Root对象中的所有可能键:

&#13;
&#13;
var j = {
    "Root": {
        "a": "1800,1200,3100",
        "b": "1500,1999,2001",
        "c": "40,60,50",
        "d": "152,199,21",
        "e": "15,19,200"
    }
};
var root = j.Root,
    l = root.a.split(",").length,
    hash = ["a", "b", "c"];


for (var i = 0; i < l; i++) {
    var obj = {};
    for (var x = 0; x < hash.length; x++) {
        obj[hash[x]] = root[hash[x]].split(",")[i];
    }
    root['row_' + i] = obj;
}


for (var x = 0; x < hash.length; x++) {
    delete root[hash[x]];
}
console.log(root);
console.log(JSON.stringify(j));
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以迭代密钥并构建新属性。

&#13;
&#13;
var object = { Root: { a: "1800,1200,3100", b: "1500,1999,2001", c: "40,60,50", d: "this is not needed", e: "nor this one" } },
    reference = object.Root;

Object
    .keys(reference)
    .forEach(k => {
        var values = reference[k].split(',');
        if (values.length === 1) {
            return;
        }
        values.forEach((v, i) => {
            reference['row_' + i] = reference['row_' + i] || {};
            reference['row_' + i][k] = v;
        });        
        delete reference[k];
    });

console.log(object);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;

答案 2 :(得分:1)

您可以使用以下方法获得所需的结果

  1. reduce()
  2. match()
  3. Object.keys()
  4. Object.values()
  5. <强>样本

    const root = {
        "Root": {
          "a": "1800,1200,3100",
          "b": "1500,1999,2001",
          "c": "40,60,50",
          "d": "this is not needed",
          "e": "nor this one"
        }
      },
      hash = ["a", "b", "c"],
      keys = Object.keys(root.Root);
    
    
    let result = Object.values(root.Root).reduce((obj, value, index) => {
      if (value.match(',')) {
        value = value.split(',');
        obj[`row_${index}`] = hash.reduce((object, key, index) => {
          object[key] = value[index];
          return object;
        }, {});
      } else {
        obj[keys[index]] = value;
      }
      return obj;
    }, {})
    
    console.log(result);