Wednesday, December 29, 2021

JS separate out / remove attributes from an Object

I needed to separate out attributes to save for query parameters, and other settings separately.  So instead of looping through filters twice to remove what I needed to populate query parameters and other settings, do it once:

const filters = [
  {
    type: "type1",
    ids: [22,33,44,55],
    other1: { testdata: "hi" },
    other2: true,
    other3: false,
    other4: ["you"],
  },
  {
    type: "type2",
    ids: [66,77,88],
    other1: { testdata: "howdy" },
    other2: false,
    other3: true,
    other4: ["there"],
  }
];
const otherSettings = [];
const queryParams = [];
filters.forEach(filter => {
  const { ids, type, ...otherSetting } = filter;
  const queryParam = {
    ids,
    type
  };
  otherSettings.push(otherSetting);
  queryParams.push(queryParam);
});
console.log(`queryParams:${JSON.stringify(queryParams)}, otherSettings:${JSON.stringify(otherSettings)}`);

Output

queryParams: [{
        "ids": [22, 33, 44, 55],
        "type": "type1"
    }, {
        "ids": [66, 77, 88],
        "type": "type2"
    }
], otherSettings: [{
        "other1": {
            "testdata": "hi"
        },
        "other2": true,
        "other3": false,
        "other4": ["you"]
    }, {
        "other1": {
            "testdata": "howdy"
        },
        "other2": false,
        "other3": true,
        "other4": ["there"]
    }
]

No comments:

Post a Comment

I appreciate your time in leaving a comment!