将嵌套的json对象转换为一个对象?

31moq8wy  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(410)

这个问题在这里已经有答案了

合并/展平数组(83个答案)
两年前关门了。
我从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
     }

 ]
qjp7pelc

qjp7pelc1#

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

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 我的答案中的方法(;
额外:让我们用两种方法扩展数组的原型

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>
bxfogqkk

bxfogqkk2#

使用 [].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))

相关问题