Как уничтожить свойства объекта с помощью фильтра или уменьшить es6? - PullRequest
0 голосов
/ 16 мая 2019

Пытаясь удалить свойства объекта, используя метод 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 ]

1 голос
/ 16 мая 2019

Вы можете использовать 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);

Карта перебирает каждый элемент в данном массиве и возвращает новый массив.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

0 голосов
/ 17 мая 2019
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;
}
0 голосов
/ 17 мая 2019

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);
0 голосов
/ 16 мая 2019

Привет @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
        }
    }
})

0 голосов
/ 16 мая 2019

Если вы хотите изменить исходный список в строке, вы можете рекурсивно удалить ключи, используя ссылку на объект следующим образом:

{
  "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;
}
0 голосов
/ 16 мая 2019

Попробуй так:

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);
0 голосов
/ 16 мая 2019

Вы можете просто сделать:

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

            return {
                ... newA,
                mailPrice: {
                    prop2: a.mailPrice.prop2
                },
                retailPrice: {
                    prop2: a.retailPrice.prop2
                }
            }
        }
    )
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...