如何使用es6的filter或reduce破坏对象属性?

时间:2019-05-16 16:55:39

标签: javascript arrays ecmascript-6

尝试使用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"
        }
    }

]

7 个答案:

答案 0 :(得分:1)

您可以使用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

答案 1 :(得分:0)

您可以简单地做到:

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

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

答案 2 :(得分:0)

尝试这样:

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);

答案 3 :(得分:0)

如果您想直接修改原始列表,则可以使用如下对象引用来递归删除键:

{
  "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;
}

答案 4 :(得分:0)

您好,@ 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
        }
    }
})

答案 5 :(得分:0)

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);

答案 6 :(得分:0)

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;
}