json 如何将数组对象转换为特定格式的对象数据

6yjfywim  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(124)

对不起,这是第一次发布问题,如果有不礼貌的地方,我会修改的。
我是一个编程新手,我使用node.js和mysql。
我在数据库里找到了这个数据:

[{"id":230,"a":1,"b":0,"c":0},{"id":232,"a":1,"b":0,"c":0},{"id":234,"a":0,"b":1,"c":0},{"id":236,"a":1,"b":0,"c":0},{"id":238,"a":0,"b":1,"c":0},{"id":240,"a":0,"b":1,"c":0},{"id":242,"a":0,"b":0,"c":1}]

这是我期望的格式:

{"col1":{"a":2},"col2":{"b":1}, "col3":{"a":1},"col4":{"b":2, "c":2} }

只有一个1将出现在a、b和c的键值中。它将从col1开始。如果下一个数据的值与上一个数据不同,则将添加新的col2。如果是相同的,它将被添加到当前的列数中。
如果遇到c:1,则不添加新的col,它将添加到当前col中
下面是我的代码:

let results = [{"id":230,"a":1,"b":0,"c":0},{"id":232,"a":1,"b":0,"c":0},{"id":234,"a":0,"b":1,"c":0},{"id":236,"a":1,"b":0,"c":0},{"id":238,"a":0,"b":1,"c":0},{"id":240,"a":0,"b":1,"c":0},{"id":242,"a":0,"b":0,"c":1}]

      let BigRoad = {
        "col1": {},
        "col2": {},
        "col3": {},
        "col4": {},
        "col5": {},
        "col6": {},
        ..........
        "colN": {},
      }

      for (let i=0; i < results.length; i++) {
        //Loop to the first results. BigRoad.col1 if there is no value, it will match the following two if conditions
        if (results[i].a && Object.keys(BigRoad.col1).length == 0) {
          BigRoad.col1.a = results[i].a
        }
        if (results[i].b && Object.keys(BigRoad.col1).length == 0) {
          BigRoad.col1.b = results[i].b
        }
      }

      console.log(BigRoad)
      //output: { col1: { a: 1 }, col2: {}, col3: {}, col4: {}, col5: {}, col6: {} }

我不知道如何使用这个if方法来合成我想要的数据。

q35jwt9p

q35jwt9p1#

let results = [{
  "id": 230,
  "a": 1,
  "b": 0,
  "c": 0
}, {
  "id": 232,
  "a": 0,
  "b": 0,
  "c": 0
}, {
  "id": 234,
  "a": 0,
  "b": 1,
  "c": 0
}, {
  "id": 236,
  "a": 1,
  "b": 0,
  "c": 0
}, {
  "id": 238,
  "a": 0,
  "b": 1,
  "c": 0
}, {
  "id": 240,
  "a": 0,
  "b": 1,
  "c": 0
}, {
  "id": 242,
  "a": 0,
  "b": 1,
  "c": 1
}]

let bigRoad = {};
results && results.map((e, i) => {
  for (let x in e) {
    if (x !== 'id') {
      if (e[x]) {
        if (bigRoad.hasOwnProperty(`col${i}`)) {
          bigRoad[`col${i}`][`${x}`] = e[x]
        } else {
          bigRoad[`col${i}`] = {
            [`${x}`]: e[x]
          }
        }
      }
    }
  }
});
console.log(bigRoad);

相关问题