Loading...

How merge mutil object in array with lodash?


I have a bit of problems with my code :

[
 {
 "key": 0,
 "server": 0
 },
 {
 "key": 0,
 "server": 1
 },
 {
 "key": 1,
 "server": 0
 }
]

how i can result to :

[
 { key: 0 , server:[0,1] },
 { key: 1 , server:[0] }
]

I'm using _.groupBy but it does not return results as expected. How merge mutil object in array with lodash?

- - Source

Answers

answered 1 week ago Hùng Phong #1

Haven't tested yet

arr.reduce(function(acc,value){
    const isExists = acc.findIndex(({key})=>key===value.key)
    if(!isExists){
        acc.push(value)
    } else {
        let servers = acc[isExists].server
        if(!Array.isArray(servers))
            servers = [servers]
        servers.push(value.server)
        servers = _.uniq(servers)
        acc[isExists].server = servers
    }
    return acc
},[])

answered 1 week ago Ana Liza Pandac #2

One solution would be to use a combination of groupBy, map, and mergeWith.

So first, you group the items by key, so in this example it will return an object with 0 and 1 as the keys which will contain the grouped items.

Then you use .map to iterate through the returned object and get the grouped values.

Finally, you use .mergeWith with a customizer function which you can use to customize the how the values of the server key is merged.

const servers = [{
    "key": 0,
    "server": 0
  },
  {
    "key": 0,
    "server": 1
  },
  {
    "key": 1,
    "server": 0
  }
];

function customizer(objValue, srcValue, key, fourth) {
  if (key === 'server') {
    if (!_.isArray(objValue)) objValue = [objValue];
    return objValue.concat(srcValue);
  }
}

let test = _(servers)
  .groupBy('key')
  .map((values, key) => {
    if (values.length === 1) {
      values[0].server = [values[0].server];
      return values[0];
    }
    return _.mergeWith(...values, customizer);
  })
  .value();

console.log(test);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

answered 1 week ago Đại Lão Gia #3

new Vue({
  el: "#app",
  data: {
    needMergedArray: [
 {
    key: 0,
    server: 0
 },
  {
 key: 0,
 server: 1
 },
 {
 key: 1,
 server: 0
 }
],
  },
  methods: {
    mergeObject() {
        let merged = [];
      this.needMergedArray.map(item => {
        let found = false;
        merged.map(element => {
            if(item.key === element.key) {
            found = true;
            if(!element.server) {
              //const myserver = [item.server];
             element.server =[item.server];
                        } else {
              element.server.push(item.server);
                }
                }
            });
        if(!found) {
            const myserver = [item.server];
            merged.push({key: item.key, server: myserver});
        }
        found = false;
      });
        return merged;
    }
  }
})

answered 1 week ago Đại Lão Gia #4

// one loop solution: https://jsfiddle.net/haianhnc/2mhsquad/78

mergeObject() { 
        let merged = {};
            this.needMergedArray.map(item => {
          merged = {...merged, [item.key]: {key: [item.key], server: (merged[item.key] && merged[item.key].server || []).concat(item.server)}};
        });
        return Object.values(merged);
      }
    }

comments powered by Disqus