【问题标题】:Getting values from JSON object against key根据键从 JSON 对象中获取值
【发布时间】:2018-08-09 17:10:29
【问题描述】:

我试图解析 json 对象但遇到了困难。 这就是我想要做的事情

var dat = {array:test};
    console.log("testing" + JSON.stringify(dat.array[0]));
    for(var i = 0; i < dat.array.length; i++) {
        console.log("testing" + JSON.stringify(dat.array[i]));
    }

数据位于从数据库获取数据的“测试”变量中。测试对象如下

 [ [ { id: 123456,
      Key 1: ‘some value’,
      Key 2: ‘another  value’,
      Key 3: 'Frontpage'
} ],
  [ { id: 123456,
      Key 1: ‘some value’,
      Key 2: ‘another  value’,
      Key 3: 'Frontpage'
 } ] ]

我需要针对每个键获得价值。 预期输出

{ id: 123456,
      Key 1: ‘some value’,
      Key 2: ‘another  value’,
      Key 3: 'Frontpage'
 }

【问题讨论】:

  • 能否提供运行代码时的预期输出?
  • 更新问题
  • test的数据类型是什么?是 JavaScript 数组还是 JSON 编码的字符串变量?
  • javascript 数组
  • “test”中的数据写在上面

标签: json node.js parsing hapijs


【解决方案1】:

如果我正确理解了您的问题,希望这段代码对您有所帮助:

const assert = require('assert')

const test = [
  [
    {
      'id': 123456,
      'Key 1': 'some value',
      'Key 2': 'another  value',
      'Key 3': 'Frontpage'
    }
  ],
  [
    {
      'id': 123456,
      'Key 1': 'some value',
      'Key 2': 'another  value',
      'Key 3': 'Frontpage'
    }
  ]
]

const expected = [{
  'id': 123456,
  'Key 1': 'some value',
  'Key 2': 'another  value',
  'Key 3': 'Frontpage'
},
{
  'id': 123456,
  'Key 1': 'some value',
  'Key 2': 'another  value',
  'Key 3': 'Frontpage'
}]

const dat = { array: test }
const actual = dat.array.reduce((p, n, index) => p.concat(n[index - 1]))

// test
assert.deepEqual(actual, expected)

【讨论】:

    【解决方案2】:
    var test = [
      [{
        id: 123456,
        Key1: "some value",
        Key2: "another  value",
        Key3: "Frontpage"
      }],
      [{
        id: 123456,
        Key1: "some value",
        Key2: "another  value",
        Key3: "Frontpage"
      }]
    ]
    
    
    
    var dat = { array: test };
    test.forEach(function (elem) {
      elem.forEach(function (obj) {
        console.log(obj)
      })
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-25
      • 1970-01-01
      • 2021-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      相关资源
      最近更新 更多