将嵌套的JSON对象转换为只有一个对象?

时间:2018-06-13 15:34:53

标签: javascript mysql json node.js

我从node.js中使用mysql db获取此JSON结果。

[
   [
     {
      val1:1,
      val2:2,
      val3:3
     }
  ],
  [
    {
      val1:1,
      val2:2,
      val3:3
    }
 ],
 [
    {
      val1:1,
      val2:2,
      val3:3
    }
 ]
]

我想转换成以下格式,但我无法将所有josn对象转换为一个json对象。

   [ 
     {
      val1:1,
      val2:2,
      val3:3
     },
     {
      val1:1,
      val2:2,
      val3:3
     },
     {
      val1:1,
      val2:2,
      val3:3
     }

 ]

2 个答案:

答案 0 :(得分:3)

使用[].concat.apply([], array)



var arr = [[{val1:1,val2:2,val3:3}],[{val1:1,val2:2,val3:3}],[{val1:1,val2:2,val3:3}]]

console.log([].concat.apply([], arr))




答案 1 :(得分:1)

对于嵌套数组中不只有一个对象的情况:

const arrayOfArrays = [
  [{val1:1, val2:2, val3:3}, {val1:1, val2:2, val3:3, val4:4}, {val1:1, val2:2, val3:3, val4:4}],
  [{val1:1, val2:2, val3:3}, {val1:1, val2:2, val3:3, val4:4}],
  [{val4:4, val3:3, val2:2, val1:1}],
  [{val2:2, val1:1, val3:3}, {val3:3, val2:2, val1:1, val4:4}]
]

const arrayOfObjects = [].concat.apply([], arrayOfArrays);

console.log('Flattened:', arrayOfObjects);

const normalizeObject = obj => _(obj).toPairs().sortBy(0).fromPairs().value();

const removeDuplicates = function(array) {
  return [
    ...new Set(
      array.map(item => JSON.stringify(normalizeObject(item)))
    )
  ].map(item => JSON.parse(item));
};

const arrayOfUniqueObjects = removeDuplicates(arrayOfObjects);

console.log('Unique:', arrayOfUniqueObjects);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>

奖励:在我的回答中检查removeDuplicates方法(;



EXTRA:让我们用2种方法扩展Array的原型

const normalizeObject = obj => _(obj).toPairs().sortBy(0).fromPairs().value();

Array.prototype.flattenNested = function() {
  return [].concat.apply([], this);
}

Array.prototype.removeDuplicateObjects = function() {
  return [
    ...new Set(
      this.map(item => JSON.stringify(normalizeObject(item)))
    )
  ].map(item => JSON.parse(item));
}


const arrayOfArrays = [
  [{val1:1, val2:2, val3:3}, {val1:1, val2:2, val3:3, val4:4}, {val1:1, val2:2, val3:3, val4:4}],
  [{val1:1, val2:2, val3:3}, {val1:1, val2:2, val3:3, val4:4}],
  [{val1:1, val2:2, val3:3, val4:4}, {val3:3, val1:1, val2:2}, {val3:3, val2:2, val1:1, val4:4}]
]

const arrayOfObjects = arrayOfArrays.flattenNested();

console.log('Flattened:', arrayOfObjects);


const arrayOfUniqueObjects = arrayOfObjects.removeDuplicateObjects();

console.log('Unique:', arrayOfUniqueObjects);
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>