簡體   English   中英

如何從嵌套的每個數組中刪除一個公共屬性

[英]How to remove a common property from each array which is nested

我有一個如下數組:我想刪除origin:0屬性,並使用Javascript es6功能直接添加它的值。 如何從嵌套數組中刪除相同的重復屬性。

const orginalData = {
  name: {
    origin: 0,
    value: 'christi'
  },
  location: {
    origin: 0,
    value: 'Blr'
  },
  address: {
    origin: 0,
    value: [{
        "streetAddress1": {
          "origin": 0,
          "value": '12th street'
        },
        "city1": {
          "origin": 0,
          "value": 'Maxwell'
        }
      },
      {
        "streetAddress2": {
          "origin": 0,
          "value": '10=]]]]]]]th street'
        },
        "city2": {
          "origin": 0,
          "value": 'Coxwell'
        }
      }
    ]
  }
}
const finalData = {
  name: 'christi',
  location: 'Blr',
  address: [{
      streetAddress1: '10th street',
      city1: 'Maxwell'
    },
    {
      streetAddress2: '12th street',
      city2: 'Coxwell'
    }
  ]
}

您可以像這樣創建通用函數。 reduce對象的entries以刪除嵌套級別並使用嵌套value更新。 如果value是一個數組,則使用map遞歸地在每個對象上調用該函數,並獲取一個重組對象的數組。 這適用於任何級別的嵌套

 const orginalData={name:{origin:0,value:"christi"},location:{origin:0,value:"Blr"},address:{origin:0,value:[{streetAddress1:{origin:0,value:"12th street"},city1:{origin:0,value:"Maxwell"}},{streetAddress2:{origin:0,value:"10=]]]]]]]th street"},city2:{origin:0,value:"Coxwell"}}]}}; function restructure(obj) { return Object.entries(obj).reduce((acc, [k, { value }]) => { acc[k] = Array.isArray(value) ? value.map(restructure) : value; return acc; }, {}) } const finalData = restructure(orginalData) console.log(finalData) 

如果使用的是NodeJ,則可以使用omit-deep刪除所需的任何屬性,無論該屬性在對象中的位置如何。

例如,這:

const omitDeep = require('omit-deep');

const data = {
  name: { origin: 0, value: 'christi' },
  location: { origin: 0, value: 'Blr' },
  address: {
    origin: 0,
    value: [
      { streetAddress1: { origin: 0, value: '12th street' }, city1: { origin: 0, value: 'Maxwell' } },
      { streetAddress2: { origin: 0, value: '10=]]]]]]]th street' }, city2: { origin: 0, value: 'Coxwell' } }
    ]
  }
};

const finalData = omitDeep(data, 'origin');

產生以下結果:

{
  name: { value: 'christi' },
  location: { value: 'Blr' },
  address: {
    value: [
      { streetAddress1: { value: '12th street' }, city1: { value: 'Maxwell' } },
      { streetAddress2: { value: '10=]]]]]]]th street' }, city2: { value: 'Coxwell' } }
    ]
  }
};

首先,如果要編輯數據,則不能是const,因此請通過let或var更改const。 第二,您可以使用for循環來做到這一點,您只需編寫一個函數或向JSON對象添加一個函數


// first logique as global function
function keepKey(data, keep) {
    for(let key in data) data[key] = data[key][keep];
}

// second logique as global function
function removeKey(data, remove, assignRest) {
    for(let key in data){
        //get the item
        let item = data[key];

        if(typeof item === 'object'){
            //if you put 'use strict' at the top you have to use a loop
                let temp = {}, lastKey = '';
                for(let itemKey in item){
                    if(itemKey !== remove){
                        if(assignRest === true) temp = item[itemKey];
                        else temp[itemKey] = item[itemKey];
                    }
                }
                data[key] = temp;

            //else you can use directly delete
                //delete item[remove];
        }
    }
}


// add the function to JSON object
JSON.keepKey = {...function...}
// or
JSON.removeKey = {...function...}


JSON.keepKey(orginalData, 'value');
// will give you 
{name: 'christi',location: 'Blr',...}


JSON.removeKey(orginalData, 'value', true);
// will give you 
{name: 'christi',location: 'Blr',...}


JSON.removeKey(orginalData, 'value', false);
// will give you 
{name: {value : 'christi'},location: {value: 'Blr'},...}

const finalData = {
  // ...originalData, uncommnent this if you have more originalData has props that you do not want to chnage.
  name: originalData.name.value,
  location: originalData.location.value,
  address: originalData.address.value.map(item => {
    const { origin, ...rest } = item;

    return rest;
  }),
};

這只是adiga邏輯的一個副本,並通過多余的標識符和注釋使其更加明確。

旨在幫助您了解reduce方法(以及其他JavaScript功能)和遞歸。

 const originalData = { name: { origin: 0, value: 'christi' }, location: { origin: 0, value: 'Blr' }, address: { origin: 0, value: [ { "streetAddress1": { "origin": 0, "value": '12th street' }, "city1": { "origin": 0, "value": 'Maxwell' } }, { "streetAddress2": { "origin": 0, "value": '10=]]]]]]]th street' }, "city2": { "origin": 0, "value": 'Coxwell' } } ] } }; function restructure(obj) { // Whether `restructure` is called directly or recursively, it builds and returns // a new object. return Object.entries(obj).reduce( (acc, curr, ind, arr ) => { // Here, `entries` is a 2D array where each 'row' is a property and the two // 'columns' are the property name and property value. // We identify them explicitly below and assume that that the property value // is an object with a subproperty called "value", which we also identify. const propKey = curr[0], propVal = curr[1], subpropVal = propVal["value"]; // Logs the index (ie 'row' number) of the current property and its property name //console.log(ind, propKey); // Here, `acc` is the object we will return. We give `acc` a new property with // the same name as the current property. // If the "value" subproperty of the current property holds an array, the new // property will hold an array of objects, each of which is a `restructure`d // version of an object from the source array. (This can happen many times, // restructuring nested objects from many nested arrays.) // If not, the new property will have the same value as the "value" subproperty does acc[propKey] = Array.isArray(subpropVal) ? subpropVal.map(restructure) : subpropVal; // If this call to `restructure` was recursive, we will continue looping through // the array we are currently processing. // If this was the original call, we're done and log our `finalData` to the console. return acc; }, {}) } const finalData = restructure(originalData); console.log(finalData); 

暫無
暫無

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

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