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

时间:2017-10-11 14:47:52

标签: 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,一个数组等于另一个,但我仍然得到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);
          }
}

我在评论中修改了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中的数据没有引号或尾随的双引号。但是...

这是我在DEV CONSOLE中得到的:

注意,没有DBL QUOTE ADDED用于前导或尾随: enter image description here enter image description here

然后,当我点击NEXT级别时,会添加DOUBLE QUOTES,从而弄乱了尝试访问:getResults.strains.map()...

enter image description here

最后,产生错误......

enter image description here

那么,我哪里错了?

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

4 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

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

答案 2 :(得分:1)

我的解决方案:

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)"}]

答案 3 :(得分:0)

for (n of strains) {
    n = n.filter(function(elem,index){
        return (index == "id" || index == "label")
    });
}

那样的东西?