根据键从JSON对象获取值

时间:2018-08-09 07:18:21

标签: json node.js parsing hapijs

我试图解析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]));
    }

数据位于“测试”变量中,该变量从DB获取数据。测试对象如下

 [ [ { 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'
 }

2 个答案:

答案 0 :(得分:0)

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

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)

答案 1 :(得分:0)

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)
  })
})
相关问题