Удалить / добавить свойства объекта - PullRequest
0 голосов
/ 30 января 2020

У меня трудности с выполнением простой задачи, и я не могу понять это, я был бы рад, если кто-то может помочь.

У меня есть объект с несколькими свойствами, и я хочу отфильтровать некоторые из свойств. Я создал массив со свойствами, которые я хочу отфильтровать из объекта.

const str = `
{"id":63,"parent_id":0,"number":"63","order_key":"wc_order_JQR7ZXgFWE4MU","created_via":"admin","version":"3.9.1","status":"pending","currency":"GBP","date_created":"2020-01-30T14:07:52","date_created_gmt":"2020-01-30T14:07:52","date_modified":"2020-01-30T14:08:04","date_modified_gmt":"2020-01-30T14:08:04","discount_total":"0.00","discount_tax":"0.00","shipping_total":"0.00","shipping_tax":"0.00","cart_tax":"0.00","total":"0.00","total_tax":"0.00","prices_include_tax":false,"customer_id":0,"customer_ip_address":"","customer_user_agent":"","customer_note":"","billing":{"first_name":"asfaf","last_name":"asfaf","company":"","address_1":"","address_2":"","city":"","state":"","postcode":"","country":"GB","email":"asasfasf@eta.com","phone":"14124"},"shipping":{"first_name":"","last_name":"","company":"","address_1":"","address_2":"","city":"","state":"","postcode":"","country":""},"payment_method":"","payment_method_title":"","transaction_id":"","date_paid":null,"date_paid_gmt":null,"date_completed":null,"date_completed_gmt":null,"cart_hash":"","meta_data":[],"line_items":[],"tax_lines":[],"shipping_lines":[],"fee_lines":[],"coupon_lines":[],"refunds":[],"_links":{"self":[{"href":"https:\/\/example.com\/wp-json\/wc\/v3\/orders\/63"}],"collection":[{"href":"https:\/\/example.com\/wp-json\/wc\/v3\/orders"}]}}
`;

const unwanted = ['id', 'parent_id', 'number', 'order_key', 'created_via', 'version', '_links'];
const hey = JSON.parse(str);

Поэтому я хочу вернуть объект без «нежелательных» свойств.

I ' Я также пытаюсь добавить новый параметр внутри массива, который находится внутри этого объекта. Я хочу иметь возможность вставить этот параметр в массив строк: {product_id: 123}. поэтому позиции должны выглядеть следующим образом:

line_items: [
  {
    product_id: 123
  }
]

Спасибо!

** РЕДАКТИРОВАТЬ ** Я обнаружил, что могу использовать метод удаления. unwanted.forEach (i => delete hey [i]);

Теперь я пытаюсь выяснить, как я могу добавить объект в массив внутри этого объекта. спасибо!

Ответы [ 2 ]

0 голосов
/ 30 января 2020

Итак, я узнал, как добиться того, чего я хочу :) Вот мои выводы:

// remove
unwanted.forEach(i => delete hey[i]);

// add
hey.line_items.push({ product_id: 123 });
0 голосов
/ 30 января 2020

Вы можете использовать filter();

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

const str = `
{"id":63,"parent_id":0,"number":"63","order_key":"wc_order_JQR7ZXgFWE4MU","created_via":"admin","version":"3.9.1","status":"pending","currency":"GBP","date_created":"2020-01-30T14:07:52","date_created_gmt":"2020-01-30T14:07:52","date_modified":"2020-01-30T14:08:04","date_modified_gmt":"2020-01-30T14:08:04","discount_total":"0.00","discount_tax":"0.00","shipping_total":"0.00","shipping_tax":"0.00","cart_tax":"0.00","total":"0.00","total_tax":"0.00","prices_include_tax":false,"customer_id":0,"customer_ip_address":"","customer_user_agent":"","customer_note":"","billing":{"first_name":"asfaf","last_name":"asfaf","company":"","address_1":"","address_2":"","city":"","state":"","postcode":"","country":"GB","email":"asasfasf@eta.com","phone":"14124"},"shipping":{"first_name":"","last_name":"","company":"","address_1":"","address_2":"","city":"","state":"","postcode":"","country":""},"payment_method":"","payment_method_title":"","transaction_id":"","date_paid":null,"date_paid_gmt":null,"date_completed":null,"date_completed_gmt":null,"cart_hash":"","meta_data":[],"line_items":[],"tax_lines":[],"shipping_lines":[],"fee_lines":[],"coupon_lines":[],"refunds":[],"_links":{"self":[{"href":"https:\/\/example.com\/wp-json\/wc\/v3\/orders\/63"}],"collection":[{"href":"https:\/\/example.com\/wp-json\/wc\/v3\/orders"}]}}
`;

const unwanted = ['id', 'parent_id', 'number', 'order_key', 'created_via', 'version', '_links'];

const obj = JSON.parse(str);


const output = Object.keys(obj).reduce((prev, key) => {
   if (unwanted.indexOf(key) > -1 ) {
     prev[key] = obj[key];
   }
   return prev;
}, {});

console.log(output);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...