繁体   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