简体   繁体   中英

How to merge/combining multiple Object into Array

im looking best way to merge object into array.. this my issue :

Object {
  "payload": Array [
    Object {
      "category": "kontrakan",
    },
    Object {
      "Tenant": "anji",
    },
  ],
  "type": "GET_DATA_VENUE_SUCCESS",
}

Object {
  "payload": Array [
    Object {
      "category": "kost",
    },
    Object {
      "Tenant": "ade",
    },
  ],
  "type": "GET_DATA_VENUE_SUCCESS",
} 

expect transform like this :

{
  [
   {"category" : "kontrakan","Tenant" : "anji"}, 
   {"category" : "kost", "Tenant" : "ade"}
  ]
}

here code :

let obj = doc.data();
let arrObj = _.map(_.keys(obj), key => ({ [key]: obj[key] }));
console.log(arrObj);

im was already try with another solutions. object.assign/key, lodash : _.merge, union still not working perfectly...

You could use map method in combination with reduce and Object.assign for merging objects properties .

 var arr = [{ "payload": [ { "category": "kontrakan", }, { "Tenant": "anji", } ], "type": "GET_DATA_VENUE_SUCCESS", }, { "payload": [ { "category": "kost", }, { "Tenant": "ade", }, ], "type": "GET_DATA_VENUE_SUCCESS", }] var result = arr.map(({payload}) => payload.reduce((obj, item) => Object.assign(obj, item), {})); console.log(result);

The function you are looking for is reduce .

You can use reduce to combine the 'payload' data into a single object. By using a object as the accumulator.

Example:

const a = {
  payload: [{
    category: 'a'
  },
  {
    tenant: 'a'
  }]
};


function mergePayload(obj) {
  return obj.payload.reduce((newObj, payloadObj) => {
    // Create a new object with the properties of the old and the new combined
    return Object.assign(newObj, payloadObj);
  }, {});
}

// {category: "a", tenant: "a"}
console.log(mergePayload(a))

You can map an array with data to the reducer:

const data = [a, a];

// [{category: "a", tenant: "a"}, {category: "a", tenant: "a"}]
console.log(data.map((d) => mergePayload(d)));

Edit: You can make the reduce shorter, but this would no longer make room for the comment.

function mergePayload(obj) {
  return obj.payload.reduce((newObj, payloadObj) => Object.assign(newObj, payloadObj), {})
}

Assuming you have only two objects into the array and the possible properties are "category" and "Tenant"

 let arr = [{ "payload": [{ "category": "kontrakan", }, { "Tenant": "anji", }, ], "type": "GET_DATA_VENUE_SUCCESS"}, { "payload": [{ "category": "kost", }, { "Tenant": "ade", }, ], "type": "GET_DATA_VENUE_SUCCESS"}], result = arr.map(({payload: [{category: category}, {Tenant: tenant}]}) => ({category, tenant})); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM