簡體   English   中英

如何提取對象數組中每個對象的兩個元素並制作一個新元素

[英]How can I pull out two elements of every object in an array of objects and make a new one

我有一個數組,它的長度可以隨時> 1,並且會不斷變大。

我只需要提取父數組元素的兩個值,然后將它們放入新數組中。

這是基本數組的示例:

{
    "strains":[
            {
                "id": 150,
                "name": "Animal Cookies (Phat Panda)",
                "label": "Animal Cookies (Phat Panda)",
                "thcpct": 14,
                "cbdpct": 19,
                "ttlpct": 33,
                "type": "Hybrid SD",
                "subtype": "Sativa Dominant",
                "bitactive": 1,
                "useradded": "jjones",
                "dateadded": "4/12/2017"
            },
            {
                "id": 110,
                "name": "Blue Dream (Pioneer)",
                "label": "Blue Dream (Pioneer)",
                "thcpct": 24,
                "cbdpct": 0,
                "ttlpct": 24,
                "type": "Sativa",
                "subtype": "None",
                "bitactive": 1,
                "useradded": "jjones",
                "dateadded": "3/27/2017"
            },
            {
                "id": 30,
                "name": "Candyland",
                "label": "Candyland",
                "thcpct": 25,
                "cbdpct": 75,
                "ttlpct": 100,
                "type": "Hybrid SD",
                "subtype": "Sativa Dominant",
                "bitactive": 1,
                "useradded": "jjones",
                "dateadded": "1/1/2017"
            },
            {
                "id": 130,
                "name": "Dragon OG (Avitas)",
                "label": "Dragon OG (Avitas)",
                "thcpct": 26,
                "cbdpct": 18,
                "ttlpct": 44,
                "type": "Hybrid SD",
                "subtype": "Sativa Dominant",
                "bitactive": 1,
                "useradded": "jjones",
                "dateadded": "4/10/2017"
            }
    ]
}

這是我希望提取后的樣子:

{
    "strains":[
            {
                "id": 150,
                "label": "Animal Cookies (Phat Panda)",
            },
            {
                "id": 110,
                "label": "Blue Dream (Pioneer)",
            },
            {
                "id": 30,
                "label": "Candyland",
            },
            {
                "id": 130,
                "label": "Dragon OG (Avitas)",
            }
    ]
}

我嘗試執行此操作的方法是使用push,一個數組等於另一個,但仍然得到Push不是函數,或者'id'未定義並且代碼停止。

這是EASY STUFF,將一個數組元素分配給另一個並不難,但是為什么這種情況如此不同?

我有在這里嘗試過的示例代碼:

我試過在這里使用LODASH:

//This is the call to the FIX_KEY function in appservice
  _.object(
     _.map(
      _.keys(allStrains.data),
         ctrlMain.appSvc.appFuncs.fix_key(/^name/, 'label')),
      _.values(allStrains.data)
  );

這是appservice中的函數:

svc.appFuncs = {
  //https://stackoverflow.com/questions/32452014/change-key-name-in-javascript-object
  //This replaces a STATIC key value for now, but can probably
  //replace any value
          fix_key: function (key, keyname) {
             return key.replace(key, keyname);
          }
}

我在注釋中的堆棧溢出問題中修改了lodash代碼。

更新1:

安德列茲(Andrjez),請查看最終結果,了解我如何進行這項工作以及在哪里遇到問題:

             * Angular Dropdown Multi-select
             *
             * For STRAINS to select what will be in the room selected
             *
             */
            $scope.example8model = [];

            //Get the data from LOCALSTORAGE
            var getResults;
            **//I GET THE RESULTS from LOCAL STORAGE HERE**
            getResults = storageLocalService.getItemJSON("allstrains");
            **//CHECK the strains from LOCAL STORAGE**
            console.log("Strains: ", getResults.strains); //FAILS HERE!!!
            //getResults.strains is UNDEFINED but getResults HOLDS the JSON
            //EXACTLY how you made it in your example. I just changed
            //**obj** to **getResults**.



            var result = {
                //NEXT LINE FAILS: getResults.strains.map is UNDEFINED!    
                strains: getResults.strains.map(function (item) {
                    return {
                        id: item.id,
                        label: item.label
                    };
                })
            };

            console.log("All extracted Strains: ", result);

            $scope.example8model = result;

            //$scope.example8data = [
            //    {id: 1, label: "David"},
            //    {id: 2, label: "Jhon"},
            //    {id: 3, label: "Danny"}
            //];
            $scope.example8settings = {
                checkBoxes: true
            };

這是問題所在:LOCAL STORAGE中的數據在開頭或結尾都沒有雙引號。 但...

這是我在DEV CONSOLE中得到的:

請注意,沒有為前導或尾隨添加DBL QUOTE: 在此處輸入圖片說明 在此處輸入圖片說明

然后,當我單擊到下一級時,會添加雙引號,從而使嘗試訪問變得混亂:getResults.strains.map()...

在此處輸入圖片說明

最后,產生的錯誤...

在此處輸入圖片說明

那么,我哪里出問題了?

注意:這就是我要實現的: 多重選擇

使用Array.prototype.map

var result = { 
    strains: obj.strains.map(function (item) {
        return {
          id: item.id,
          label: item.label
        }; 
    })
};

嘗試下面的代碼片段以查看結果:

 var obj = { "strains":[ { "id": 150, "name": "Animal Cookies (Phat Panda)", "label": "Animal Cookies (Phat Panda)", "thcpct": 14, "cbdpct": 19, "ttlpct": 33, "type": "Hybrid SD", "subtype": "Sativa Dominant", "bitactive": 1, "useradded": "jjones", "dateadded": "4/12/2017" }, { "id": 110, "name": "Blue Dream (Pioneer)", "label": "Blue Dream (Pioneer)", "thcpct": 24, "cbdpct": 0, "ttlpct": 24, "type": "Sativa", "subtype": "None", "bitactive": 1, "useradded": "jjones", "dateadded": "3/27/2017" }, { "id": 30, "name": "Candyland", "label": "Candyland", "thcpct": 25, "cbdpct": 75, "ttlpct": 100, "type": "Hybrid SD", "subtype": "Sativa Dominant", "bitactive": 1, "useradded": "jjones", "dateadded": "1/1/2017" }, { "id": 130, "name": "Dragon OG (Avitas)", "label": "Dragon OG (Avitas)", "thcpct": 26, "cbdpct": 18, "ttlpct": 44, "type": "Hybrid SD", "subtype": "Sativa Dominant", "bitactive": 1, "useradded": "jjones", "dateadded": "4/10/2017" } ] }; var result = { strains: obj.strains.map(function (item) { return { id: item.id, label: item.label }; }) }; console.log(result); 

如果您想使用es6功能:

const result = { strains: obj.strains.map(({id , label}) => ({id, label})) };
obj.strains = obj.strains.map(x => ({ id: x.id, label: x.label }));

如果不僅是應變,還想對每個子數組應用相同的邏輯:

let filtered = Object.entries(obj)
  .filter(([k, arr]) => Array.isArray(arr))
  .reduce((acc, [k, arr]) => {
    acc[k] = arr.map(x => ({ id: x.id, label: x.label }));
    return acc;
  }, {});

我的解決方案:

var test = 'label'
var results = [];
var response = strains.forEach( obj => {
    if (obj[test]) {
        results = [
            ...results,
            {
                test: obj[test]
            }
        ];
    }
});

console.log('matches', results);
//output: matches, [{test: "Animal Cookies (Phat Panda)"}, {test: "Blue Dream (Pioneer)"}, {test: "Candyland"}, {test: "Dragon OG (Avitas)"}]
for (n of strains) {
    n = n.filter(function(elem,index){
        return (index == "id" || index == "label")
    });
}

這樣的東西?

暫無
暫無

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

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