簡體   English   中英

Lodash 遞歸刪除項目

[英]Lodash remove items recursively

給定這個 JSON 對象,lodash 如何從對象中刪除reach值?

{ 
    total: 350,
    SN1: { 
        reach: 200,
        engagementRate: 1.35
    },
    SN2: {
        reach: 150,
        engagementRate: 1.19
    }
}

我一直在嘗試迭代 remove() 它,但我總是得到一個未定義的對象作為回報,所以我肯定我做錯了。 這也是我第一次使用 lodash,所以這可能是實際問題。

任何人都可以幫忙嗎?

_.transform()將對象轉換為另一個對象,並在將值傳遞給新對象的同時,檢查該值是否為對象以及它是否具有 'reach' 屬性,如果是,則使用_.omit()獲取無法reach新對象:

 var obj = { total: 350, SN1: { reach: 200, engagementRate: 1.35 }, SN2: { reach: 150, engagementRate: 1.19 } }; var result = _.transform(obj, function(result, value, key) { result[key] = _.isObject(value) && `reach` in value ? _.omit(value, 'reach') : value; }); console.log(result);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

如果您需要一個遞歸解決方案來處理多個嵌套對象級別,這里是deepOmit ,它使用相同的想法,但沒有_.omit ,可用於刪除多個鍵(請參閱代碼中的注釋):

 var obj = { total: 350, SN1: { reach: 200, engagementRate: 1.35, DEEP_SN1: { reach: 200, engagementRate: 1.35 } }, SN2: { reach: 150, engagementRate: 1.19 } }; function deepOmit(obj, keysToOmit) { var keysToOmitIndex = _.keyBy(Array.isArray(keysToOmit) ? keysToOmit : [keysToOmit] ); // create an index object of the keys that should be omitted function omitFromObject(obj) { // the inner function which will be called recursivley return _.transform(obj, function(result, value, key) { // transform to a new object if (key in keysToOmitIndex) { // if the key is in the index skip it return; } result[key] = _.isObject(value) ? omitFromObject(value) : value; // if the key is an object run it through the inner function - omitFromObject }) } return omitFromObject(obj); // return the inner function result } console.log(deepOmit(obj, 'reach')); // you can use a string for a single value console.log(deepOmit(obj, ['reach', 'engagementRate'])); // you can use an array of strings for multiple values
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

似乎沒有深度omit ,但您可以遍歷對象中的所有鍵,並遞歸地從嵌套對象中刪除reach

function omitDeep(obj) {
  _.forIn(obj, function(value, key) {
    if (_.isObject(value)) {
      omitDeep(value);
    } else if (key === 'reach') {
      delete obj[key];
    }
  });
}

 var obj = { total: 350, SN1: { reach: 200, engagementRate: 1.35 }, SN2: { reach: 150, engagementRate: 1.19 } }; function omitDeep(obj) { _.forIn(obj, function(value, key) { if (_.isObject(value)) { omitDeep(value); } else if (key === 'reach') { delete obj[key]; } }); } omitDeep(obj) console.log(obj);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

_.mapValues(object, v => _.isObject(v)? _.omit(v, 'reach'): v)

_.mapValues (object, [iteratee=_.identity])

創建具有通過運行的每個自己的可枚舉的字符串鍵控屬性產生的相同的密鑰對象和值的對象objectiteratee 迭代器使用三個參數調用:( valuekeyobject )。

_.omit (object, [props])

創建的自己和繼承枚舉串鍵控屬性組成的對象object沒有被刪去。

使用_.mixin擴展 omitDeep 方法:

 _.mixin({ 'omitDeep': function(obj, predicate) { return _.transform(obj, function(result, value, key) { if (_.isObject(value)) { value = _.omitDeep(value, predicate); } var doOmit = predicate(value, key); if (!doOmit) { _.isArray(obj) ? result.push(value) : result[key] = value; } }); } }); var my = { "key1": { "key2": { "key3": [null, { "key4": "string", "key5": true, "key6": null, "key7": 8, "key7": undefined }, null] } } }; console.log(my); console.log("omit null:", _.omitDeep(my, _.isNull)); console.log("omit undefined:", _.omitDeep(my, _.isUndefined));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

通過在 ES6 + Typescript 中定義一組排除鍵,遞歸地省略對象中的鍵。

omitDeep(myObject, [omitKey1, omitKey2, ...omitKeyN])

// omitDeep.ts

/**
 * Recursively remove keys from an object
 * @usage
 *
 * const input = {
 *   id: 1,
 *   __typename: '123',
 *   createdAt: '1020209',
 *   address: {
 *     id: 1,
 *     __typename: '123',
 *   },
 *   variants: [
 *     20,
 *     {
 *       id: 22,
 *       title: 'hello world',
 *       __typename: '123',
 *       createdAt: '1020209',
 *       variantOption: {
 *         id: 1,
 *         __typename: '123',
 *       },
 *     },
 *     {
 *       id: 32,
 *       __typename: '123',
 *       createdAt: '1020209',
 *     },
 *   ],
 * }
 *
 * const output = {
 *   id: 1,
 *   address: {
 *     id: 1,
 *   },
 *   variants: [
 *     20,
 *     {
 *       id: 22,
 *       title: 'hello world',
 *       variantOption: {
 *         id: 1,
 *       },
 *     },
 *     {
 *       id: 32,
 *     },
 *   ],
 * }
 *
 * expect(omitDeep(input, ['createdAt, 'updatedAt', __typename']).to.deep.equal(output) // true
 *
 * @param {object} input
 * @param {Array<number | string>>} excludes
 * @return {object}
 */
const omitDeep = (input: object, excludes: Array<number | string>): object => {
  return Object.entries(input).reduce((nextInput, [key, value]) => {
    const shouldExclude = excludes.includes(key)
    if (shouldExclude) return nextInput

    if (Array.isArray(value)) {
      const arrValue = value
      const nextValue = arrValue.map((arrItem) => {
        if (typeof arrItem === 'object') {
          return omitDeep(arrItem, excludes)
        }
        return arrItem
      })
      nextInput[key] = nextValue
      return nextInput
    } else if (typeof value === 'object') {
      nextInput[key] = omitDeep(value, excludes)
      return nextInput
    }

    nextInput[key] = value

    return nextInput
  }, {})
}

export default omitDeep

我必須遞歸地從對象數組中刪除所有出現的兩個鍵。 omit-deep-lodash 庫允許在一行中遞歸地省略對象鍵和值。 可以在一次調用中刪除多個鍵。 對於那些覺得刪除太易變的人來說,這是一個功能性的解決方案。 請務必閱讀此處的注釋。 省略深度 lodash

const omitDeep = require("omit-deep-lodash");
 
omitDeep({a: "a", b: "b", c: {b: "b", d: {b: "b", f: "f"}}}, "b");
//=> {a: "a", c: {d: {f: "f"}}}
 
omitDeep({a: "a", b: "b", c: {b: "b", d: {b: "b", f: "f"}}}, "a", "b");

暫無
暫無

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

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