簡體   English   中英

如何使用es6的filter或reduce破壞對象屬性?

[英]How to destruct object properties using filter or reduce of es6?

嘗試使用reduce方法刪除對象屬性,但不返回預期響應,在以下用例中使用的正確方法是什么? 過濾還是減少?

main.js

const filtered = Object.keys(transformedResponse).reduce((res, key) => {

       delete res.drugName;
       delete res.mailPrice. copayEmployer
       delete res.retailPrice. copayEmployer
      return res;
    }, {});

transformedResponse

const transformedResponse = [
    {
        "isBrand": true,
        "drugName": "Lipitor",
        "drugStrength": "80 mg",
        "drugForm": "Tablet",
        "mailPrice": {
            "copayEmployer": 0,
            "prop2": "test"
        },
        "retialPrice": {
            "copayEmployer": 0,
            "prop2": "test"
        }

    }, {
        "isBrand": true,
        "drugName": "Metformin",
        "drugStrength": "500 mg",
        "drugForm": "Tablet",
        "mailPrice": {
            "copayEmployer": 50,
            "prop2": "test"
        },
        "retailPrice": {
            "copayEmployer": 0,
            "prop2": "test"
        }
    }

]

預期產量

[
    {
        "isBrand": true,
        "drugStrength": "80 mg",
        "drugForm": "Tablet",
        "mailPrice": {
            "prop2": "test"
        },
        "retialPrice": {
            "prop2": "test"
        }

    }, {
        "isBrand": true,
        "drugStrength": "500 mg",
        "drugForm": "Tablet",
        "mailPrice": {
            "prop2": "test"
        },
        "retailPrice": {
            "prop2": "test"
        }
    }

]

您可以使用map過濾出結果

var x = transformedResponse.map((obj) => {
  return {
        "isBrand": obj.isBrand,
        "drugStrength": obj.drugStrength,
        "drugForm": obj.drugForm,
        "mailPrice": {
            "prop2": obj.mailPrice.prop2
        },
        "retailPrice": {
            "prop2": obj.retailPrice.prop2
        }
  }
});

console.log(x);

Map迭代給定數組中的每個項目,並返回一個新數組。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

您可以簡單地執行以下操作:

const newTransResp = transformedResponse
    .map(
        a => {
            const {drugName, ...newA} = a;

            return {
                ... newA,
                mailPrice: {
                    prop2: a.mailPrice.prop2
                },
                retailPrice: {
                    prop2: a.retailPrice.prop2
                }
            }
        }
    )

嘗試這樣:

 const transformedResponse = [ { "isBrand": true, "drugName": "Lipitor", "drugStrength": "80 mg", "drugForm": "Tablet", "mailPrice": { "copayEmployer": 0, "prop2": "test" }, "retailPrice": { "copayEmployer": 0, "prop2": "test" } }, { "isBrand": true, "drugName": "Metformin", "drugStrength": "500 mg", "drugForm": "Tablet", "mailPrice": { "copayEmployer": 50, "prop2": "test" }, "retailPrice": { "copayEmployer": 0, "prop2": "test" } } ]; const resObj = transformedResponse.reduce((acc, curr) => { // Destructure the current object into its individual properties const { mailPrice, retailPrice, ...rest} = curr; const mailPriceObj = {}; const retailPriceObj = {}; // Extract the .prop2 property now ({ prop2: mailPriceObj.prop2 } = mailPrice); ({ prop2: retailPriceObj.prop2 } = retailPrice); // Create the projected object now const obj = { ... rest }; obj.mailPrice = { prop2: mailPriceObj.prop2 }; obj.retailPrice = { prop2: retailPriceObj.prop2 }; // Push the projected object into the accumulator acc.push(obj); return acc; }, []); console.log(resObj); 

如果要內聯修改原始列表,則可以使用對象引用來遞歸刪除鍵,如下所示:

{
  "drugName" : true,
  "mailPrice" : {
    "copayEmployer" : true
  },
  "retialPrice" : {
    "copayEmployer" : true
  }
}

注意:第一個對象中有一個錯字,即"retialPrice"而不是"retailPrice" 這就是為什么副本中不會忽略"copayEmployer"字段的原因。

 const data = getData() const ignore = { "drugName": true, "mailPrice": { "copayEmployer": true }, "retailPrice": { "copayEmployer": true } } console.log('Original:', data) console.log('Cloned:', cloneAll(data, ignore)) // Does not alter data console.log('Unmodified:', data) console.log('Pruned:', pruneAll(data, ignore)) // Alters the data console.log('Modified:', data) // Main call to pass in the list to copy items function cloneAll(data, ignoreObj) { return data.map(item => clone(item, ignoreObj)) } // Clones an object and ignores properties function clone(obj, ignoreObj) { if (obj === null || typeof(obj) !== 'object' || 'isActiveClone' in obj) { return obj } let temp = obj.constructor() for (let key in obj) { if (ignoreObj == null || ignoreObj[key] !== true) { if (Object.prototype.hasOwnProperty.call(obj, key)) { obj['isActiveClone'] = null temp[key] = clone(obj[key], ignoreObj != null ? ignoreObj[key] : null) delete obj['isActiveClone'] } } } return temp } // Main call to pass in the list to prune function pruneAll(data, ignoreObj) { return data.map(item => prune(item, ignoreObj)) } // Recursive helper method to work on each item function prune(obj, ignoreObj) { if (obj != null && ignoreObj != null) { Object.keys(ignoreObj).forEach(key => { if (ignoreObj[key] === true) { delete obj[key] // Prune property-value } else { prune(obj[key], ignoreObj[key]) } }) } return obj } function getData() { return [{ "isBrand": true, "drugName": "Lipitor", "drugStrength": "80 mg", "drugForm": "Tablet", "mailPrice": { "copayEmployer": 0, "prop2": "test" }, "retialPrice": { "copayEmployer": 0, "prop2": "test" } }, { "isBrand": true, "drugName": "Metformin", "drugStrength": "500 mg", "drugForm": "Tablet", "mailPrice": { "copayEmployer": 50, "prop2": "test" }, "retailPrice": { "copayEmployer": 0, "prop2": "test" } }] } 
 .as-console-wrapper { top: 0; max-height: 100% !important; } 

您好@hussain首先,您的數據中有錯字。 我相信第一個對象中的屬性retialPrice應該改為retailPrice 我沒有使用reduce的方法,但是map工作正常。 這是我的解決方案:

transformedResponse.map(obj => {
    return{
        isBrand:obj.isBrand,
        drugStrength: obj.drugStrength,
        drugForm: obj.drugForm,
        mailPrice: {
            prop2: obj.mailPrice.prop2
        },
        retailPrice: {
            prop2: obj.retailPrice.prop2
        }
    }
})

 const transformedResponse = [ { "isBrand": true, "drugName": "Lipitor", "drugStrength": "80 mg", "drugForm": "Tablet", "mailPrice": { "copayEmployer": 0, "prop2": "test" }, "retailPrice": { "copayEmployer": 0, "prop2": "test" } }, { "isBrand": true, "drugName": "Metformin", "drugStrength": "500 mg", "drugForm": "Tablet", "mailPrice": { "copayEmployer": 50, "prop2": "test" }, "retailPrice": { "copayEmployer": 0, "prop2": "test" } } ]; const transformed = transformedResponse.map(res => { const {drugName, mailPrice, retailPrice, ...result} = res; return {...result, mailPrice: {prop2: mailPrice.prop2}, retailPrice: {prop2: retailPrice.prop2}}; }); console.log(transformed); 

const _cloneResponse = JSON.parse(JSON.stringify(transformedResponse));
  const loggerResponse = _cloneResponse.map((data) => {
  const _response = pruneResponse(data);

    return _response;
  });

  logger().info('Drug Price Response=', { ...loggerResponse, memberId: memberId, pharmacyId: pharmacyId });

function pruneResponse (res){
  delete res.drugName;
  delete res.mailPrice.NDC11;
  delete res.retailPrice.NDC11;

  return res;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM