如何使用键和值javascript / jquery重建对象?

时间:2019-05-07 15:49:04

标签: javascript jquery

我在寻找您的建议如何在javascript / jquery中重建对象?我从服务器接收JSON

源json(可变数组):

{  
  "key1":{  
         "subkey1":"a",
         "subkey2":"b",
      },
  "key2":{  
         "subkey1":"a",
         "subkey2":"a",
      }
}

预期对象:

{  
  "a":{  
         "subkey1":[
                      "key1",
                      "key2",
                   ],
         "subkey2":[
                      "key2"
                   ]
      },
  "b":{  
         "subkey2":[
                      "key1"
                   ]
      }
}

在这里我被困住了:

    var newarray = {};
    for (var key in array) {
        var items = [];
        for (var item_id in array[key]) {
            items.push(item_id);
            newarray[array[key][item_id]] = [];
        }
        console.log(items);
    }
    console.log(newarray);

4 个答案:

答案 0 :(得分:0)

您可以采用迭代和递归的方法,并存储目标对象和下一个递归调用的路径。

如果找不到更多对象,则使用值和所有键以及实际键,并在新对象中生成新属性。继续执行对象中的所有其他属性。

警告不声明反转对象的值。此方法将undefined分配给所有叶子属性。

function setValue(object, keys, value) {
    var last = keys.pop(),
        target = keys.reduce((o, k) => o[k] = o[k] || {}, object);

    target[last] = target[last] || [];
    target[last].push(value);
}

function inverse(source, target = {}, path = []) {
    Object.entries(source).forEach(([k, v]) => {
        if (v && typeof v === 'object') return inverse(v, target, [k, ...path]);
        setValue(target, [v, k, ...path.slice(0, -1)], ...path.slice(-1));
    });
    return target;
}

var object = { key1: { subkey1: 'a', subkey2: 'b'}, key2: { subkey1: 'a', subkey2: 'a' } },
   inversed = inverse(object);
   
console.log(inversed);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

尝试(其中r = {})

The exact solution is  x = 0

Object.entries(d).map(([k,x])=> Object.entries(x).map( ([s,a]) => (
  r[a]=r[a]||{}, r[a][s]=(r[a][s]||[]).concat(k)
)))

答案 2 :(得分:0)

let input = {
  "key1": {
    "subkey1": 'a',
    "subkey2": 'b',
  },
  "key2": {
    "subkey1": 'a',
    "subkey2": 'a',
  }
};

let expected = {
  "a": {
    "subkey1": {
      key1: true,
      key2: true,
    },
    "subkey2": {
      key2: true
    }
  },
  "b": {
    "subkey2": {
      key1: true
    }
  }
};

let output = {};
Object.entries(input).forEach(([key, subObj]) => {
  Object.entries(subObj).forEach(([subKey, value]) => {
    output[value] = output[value] || {};
    output[value][subKey] = output[value][subKey] || {};
    output[value][subKey][key] = true;
  });
});

console.log(expected);
console.log(output);

答案 3 :(得分:0)

您可以尝试使用PHP样式的方法:

var newArray = {};

for (var key in array) {
    for (var subKey in array[key]) {
        var val = array[key][subKey];
        
        if (!(val in newArray)) {
            newArray[val] = {};
        }

        if (!(subKey in newArray[val])) {
            newArray[val][subKey] = [];
        }

        newArray[val][subKey].push(key);
    }
}

console.log(newArray);