【问题标题】:Convert a JSON response to a 2D matrix in JS在 JS 中将 JSON 响应转换为二维矩阵
【发布时间】:2023-02-09 17:40:52
【问题描述】:

我正在尝试以特定方式将 JSON 响应转换为矩阵,如下图所示,但没有弄明白。

我使用的 JSON 响应。

{
  "data": [{
    "type": "articles",
    "id": "1",
    "attributes": {
      "title": "JSON:API paints my bikeshed!",
      "body": "The shortest article. Ever.",
      "created": "2015-05-22T14:56:29.000Z",
      "updated": "2015-05-22T14:56:28.000Z"
    },
    "relationships": {
      "author": {
        "data": {
          "id": "42",
          "type": "people"
        }
      }
    }
  }],
  "included": [{
    "type": "people",
    "id": "42",
    "attributes": {
      "name": "John",
      "age": 80,
      "gender": "male"
    }
  }]
}

我尝试了以下代码但没有得到预期的结果。

const response = JSON.parse({
  here i used the json response
});
var arr = Object.entries(response);
var row = 1;
var col = 4;
console.log(arr[row - 1][col + 1])

【问题讨论】:

    标签: javascript algorithm matrix data-structures


    【解决方案1】:

    您可以使用这样的递归函数“展平”您的对象:

    function flatten(obj, key='', out={}) {
        for (let [k, v] of Object.entries(obj)) {
            let kr = key ? key + '.' + k : k
            if (typeof v === 'object' && v)
                flatten(v, kr, out)
            else
                out[kr] = v
        }
        return out
    }
    
    //
    
    
    res = {
        "data": [{
            "type": "articles",
            "id": "1",
            "attributes": {
                "title": "JSON:API paints my bikeshed!",
                "body": "The shortest article. Ever.",
                "created": "2015-05-22T14:56:29.000Z",
                "updated": "2015-05-22T14:56:28.000Z"
            },
            "relationships": {
                "author": {
                    "data": {
                        "id": "42",
                        "type": "people"
                    }
                }
            }
        }],
        "included": [{
            "type": "people",
            "id": "42",
            "attributes": {
                "name": "John",
                "age": 80,
                "gender": "male"
            }
        }]
    }
    
    
    console.log(flatten(res))

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-03
      • 2013-05-26
      • 1970-01-01
      • 2012-05-24
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      相关资源
      最近更新 更多