javascript - 如何从对象数组中的每个对象中取出两个元素并创建一个新元素

标签 javascript arrays

我有一个数组,其长度随时可能 > 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 is NOT a function,或者“id”未定义并且代码停止。

这很简单,将一个数组元素分配给另一个数组元素并不困难,但为什么这种情况如此不同?

我有我在这里尝试过的示例代码:

我在这里尝试使用 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)
  );

这是应用程序服务中的函数:

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);
          }
}

我修改了评论中 Stack Overflow 问题中的 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 中的数据无论是前导还是尾随都没有双引号。但是...

这是我在开发控制台中得到的内容:

注意,前导或尾随没有添加 DBL 引号: enter image description here enter image description here

然后,当我单击下一级时,会添加双引号,从而导致尝试访问变得困惑:getResults.strains.map()...

enter image description here

最后,产生的错误...

enter image description here

那么,我哪里出错了?

注意:这就是我想要实现的目标:MULTI-SELECT

最佳答案

使用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})) };

关于javascript - 如何从对象数组中的每个对象中取出两个元素并创建一个新元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46691296/

相关文章:

javascript - 返回函数 &&?

c++ - 如何在字符串数组中输入n行?

c - 每次移动后,如何在智能体周围给定本地 5x5 阵列的情况下绘制 80x80 的世界?

python - 计算 1000 个数组的统计数据

javascript - 对键绑定(bind)谷歌浏览器扩展的操作

javascript - 如何使用jquery检查输入是否检查

java - 将数组中的对象元素添加到字符串数组中

ruby-on-rails - 试图理解 sort_by 函数在 Ruby 中的工作原理

javascript - Mongoose 类型错误 : Schema is not a constructor

javascript - Angular8:全局日期格式配置