简体   繁体   English

如何提取对象数组中每个对象的两个元素并制作一个新元素

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

I have an array whose length could be > 1 at any time and just keep getting bigger. 我有一个数组,它的长度可以随时> 1,并且会不断变大。

I need to extract only TWO of the values of the parent array elements and put them into a new array. 我只需要提取父数组元素的两个值,然后将它们放入新数组中。

Here's the example of the base array: 这是基本数组的示例:

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

and this is what I want it to look like after the extraction: 这是我希望提取后的样子:

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

The way I've tried to do this is with push, one array equals another and still I get Push is NOT a function, or 'id' is undefined and the code stops. 我尝试执行此操作的方法是使用push,一个数组等于另一个,但仍然得到Push不是函数,或者'id'未定义并且代码停止。

This is EASY STUFF and assigning one array element to another is not difficult but why is this case so different? 这是EASY STUFF,将一个数组元素分配给另一个并不难,但是为什么这种情况如此不同?

I have the example code for what I've tried here: 我有在这里尝试过的示例代码:

I've tried using LODASH here: 我试过在这里使用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)
  );

Here's the function in appservice: 这是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);
          }
}

I modified a lodash code from the Stack Overflow question in the comments. 我在注释中的堆栈溢出问题中修改了lodash代码。

UPDATE 1: 更新1:

Andrjez, please see the end result on how I need to make this work and where I'm experiencing the problem: 安德列兹(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
            };

Here's the problem: The data in LOCAL STORAGE does NOT have double-quotes either leading or trailing. 这是问题所在:LOCAL STORAGE中的数据在开头或结尾都没有双引号。 BUT... 但...

This is what I get in the DEV CONSOLE: 这是我在DEV CONSOLE中得到的:

Notice, no DBL QUOTE ADDED for leading or trailing: 请注意,没有为前导或尾随添加DBL QUOTE: 在此处输入图片说明 在此处输入图片说明

Then when I click to the NEXT level down, DOUBLE QUOTES ARE ADDED thus messing up trying to access: getResults.strains.map()... 然后,当我单击到下一级时,会添加双引号,从而使尝试访问变得混乱:getResults.strains.map()...

在此处输入图片说明

Finally, the resulting Error... 最后,产生的错误...

在此处输入图片说明

So, where am I going wrong? 那么,我哪里出问题了?

NOTE: This is what I'm trying to achieve: MULTI-SELECT 注意:这就是我要实现的: 多重选择

Use Array.prototype.map : 使用Array.prototype.map

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

Try the snippet below to see the result: 尝试下面的代码片段以查看结果:

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

If you wish to use es6 features: 如果您想使用es6功能:

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

If it's more than just strains, and you want to apply the same logic to each sub array: 如果不仅是应变,还想对每个子数组应用相同的逻辑:

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

My Solution: 我的解决方案:

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

Something like that? 这样的东西?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何循环遍历 object 数组并从数组中列出的两个对象中获取一个属性元素? - How can I loop through an array of object and get one property element out of the two objects listed inside the array? 我可以使用forEach使数组的每个元素成为新对象吗? - can I use forEach to make every element of an array a new object? 如何将数组中的 object 拉出到 object 的新数组中? - How to pull out object within array to new array of object? 如何在不在 object 中创建 object 的情况下将新旧对象合并到一个数组中? - How can i merge old and new objects in one array without creating an object inside object? 如果数组元素具有对象类型,我如何删除对象? - How can i remove Objects if array elements has a object type? 如何让对象在其原型中继承两个对象? - How can I make an object inherit two objects in its prototype? 如何使用一个共享密钥从两个对象数组中创建一个对象数组-JavaScript - How to make one array of object from two array of objects with one shared key - JavaScript 用键中的数字从平面 object 中创建新的对象数组 - make new array of objects out of flat object with numbers in keys 如何在JavaScript中将两个不同的对象数组合并为一个新的对象数组? - how to combine two different array of objects into one new array of object in javascript? 在 JavaScript 中使用两个不同的 object 创建一个新的数组对象 - Make a new array objects using two different object in JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM