#javascript #node.js #arrays #object #lodash
Вопрос:
У меня есть следующий объект:
const payload = {
"content":{
"header":{
"id":"123",
"title":"Sample"
},
"footer":{
"message":"Thank you",
"version":"1.2.3.4"
},
"additionalInfo":{
"message":"contact us",
"eMail":"support@test.com"
},
"bodyFields":{
"field":[
{
"name":"price",
"values":{
"value":"100$"
}
},
{
"name":"color",
"values":{
"value":"green"
}
},
{
"name":"width",
"values":{
"value":"12cm"
}
},
{
"name":"internalCode",
"values":{
"value":"P4gh"
}
}
]
}
}
}
Моя цель состоит в том, чтобы выбирать поля только на основе предопределенных данных из белого списка и устанавливать значение других полей по умолчанию как «полученное значение».
Желаемый результат:
const payload = {
"content":{
"header":{
"id":"123",
"title":"Sample"
},
"footer":{
"message":"Thank you",
"version":"1.2.3.4"
},
"bodyFields":{
"field":[
{
"name":"price",
"values":{
"value":"value received"
}
},
{
"name":"color",
"values":{
"value":"green"
}
},
{
"name":"internalCode",
"values":{
"value":"value received"
}
},
{
"name":"width",
"values":{
"value":"12cm"
}
}
]
}
}
}
Currently, I’m using the following approach:
const whitelistContent = ['contet.header', 'content.footer'];
const whitelistBodyField = ['color', 'width'];
const filteredContent = _.pick(payload, whitelistContent);
const contentBodyField = _.get(payload, 'content.bodyFields.field');
const filteredBodyField = _.filter(contentBodyField , (field) => _.includes(whitelistBodyField, field.name));
const result = {...filteredContent, bodyFields: { fields: filteredBodyField }};
This gives (without internalCode and price fields included and their value set to default ‘value received’):
{
"content": {
"header": {
"id": "123",
"title": "Sample"
},
"footer": {
"message": "Thank you",
"version": "1.2.3.4"
}
},
"bodyFields": {
"field": [
{
"name": "color",
"values": {
"value": "green"
}
},
{
"name": "width",
"values": {
"value": "12cm"
}
}
]
}
}
Question:
- Is there a way I can merge whitelistContent and whitelistBodyField into one whitelist array and also simplify the filtering process in one go?
- How can I include the non-whitlisted properties with their value set to default string ‘value received’?