简体   繁体   English

迭代数组中的嵌套对象并删除属性名称和值

[英]Iterate over Nested Objects in Array and delete the Property names and Values

I have the array as below and what I want to do is to remove the Property names ie keys and values from the below array based on the values in the other array.我有如下数组,我想要做的是根据另一个数组中的值从下面的数组中删除属性名称,即键和值。

Options would be to create a new array as below with only values from the Keep Array or to remove the values which are not listed in the "keep" array from the original array.选项是创建一个新数组,如下所示,仅包含来自 Keep Array 的值,或者从原始数组中删除未在“keep”数组中列出的值。

var Keep=["ItemID","ItemNumber","OptionNo","Quantity","Price","Description","StockStatus","Url"]; 
var originalarray=[
      {
        "ItemID": 1,
        "ItemNumber": "611741",
        "OptionNo": "22",
        "SizeDescription": "3-6 Mths",
        "Price": "14.00",
        "Quantity": 1,
        "StockStatus": "instock",
        "StockMessage": "In Stock",
        "WarrantyItem": null,
        "Description": "Coral/Blue Embellished Two In One Dress (3mths-7yrs)",
        "Url": "/g82272s2",
        "FulfilmentType": ""
      },
      {
        "ItemID": 2,
        "ItemNumber": "912767",
        "OptionNo": "13",
        "SizeDescription": "11 EU 29",
        "Price": "16.00",
        "Quantity": 1,
        "StockStatus": "instock",
        "StockMessage": "In Stock",
        "WarrantyItem": null,
        "Description": "Silver Buckle Corkbed Sandals (Younger)",
        "Url": "/g82272s2",
        "CustomItemFields": [],
        "FulfilmentType": ""
      }
    ]

I tried to get the new array created but the array is not nested so I have multiple entries in for the same key with different values as below:我试图创建新数组,但该数组不是嵌套的,因此我在同一个键中有多个条目,具有不同的值,如下所示:

["ItemID:1", 
"ItemNumber:611741", 
"OptionNo:22", 
"Price:14.00", 
"Quantity:1", 
"StockStatus:instock", 
"Description:Coral/Blue Embellished Two In One Dress (3mths-7yrs)", "Url:/g82272s2", 
"ItemCategory:Dresses", 
"ItemID:2",
 "ItemNumber:912767", 
"OptionNo:13", 
"Price:16.00",
 "Quantity:1", 
"StockStatus:instock", 
"Description:Silver Buckle Corkbed Sandals (Younger)", 
"Url:/g82272s2", 
"ItemCategory:Sandals"]

I want the result array to be like this 

[{"ItemID:1", 
"ItemNumber:611741", 
"OptionNo:22", 
"Price:14.00", 
"Quantity:1", 
"StockStatus:instock", 
"Description:Coral/Blue Embellished Two In One Dress (3mths-7yrs)", "Url:/g82272s2", 
"ItemCategory:Dresses"}, 
{"ItemID:2",
 "ItemNumber:912767", 
"OptionNo:13", 
"Price:16.00",
 "Quantity:1", 
"StockStatus:instock", 
"Description:Silver Buckle Corkbed Sandals (Younger)", 
"Url:/g82272s2", 
"ItemCategory:Sandals"}]

This is my Code:这是我的代码:

var keep=["ItemID", "ItemNumber", "OptionNo", "Quantity", "Price", "Description", "ItemCategory", "StockStatus", "Url"],z={}; z=new Array(); y.forEach(function(arrays){
  // 4 arrays in a
  var x=Object.keys(arrays);
  var k=Object.values(arrays); 
  //console.log(x);
  //console.log(y);
for(var i = 0; i < x.length; i++) {
  //console.log(x[i]);
 keep.forEach(function(item,index,array){
      if(item==x[i]){
          //z.push(x[i]+":"+y[i]);
         z.push(x[i]+":"+k[i]);
          return z;
                    }
  })
 }
  })

Hope you can help.希望你能帮忙。

Thank you.谢谢你。

Update :更新
For the sake of it, here's the lodash version, may be easier to read, too:为此,这里是lodash版本,也可能更容易阅读:

 const keep = (k, l) => _.map(l, o => _.pick(o, k)) const keepThese = ["ItemID", "ItemNumber", "OptionNo", "Quantity", "Price", "Description", "StockStatus", "Url"] const orig = [{"ItemID": 1, "ItemNumber": "611741", "OptionNo": "22", "SizeDescription": "3-6 Mths", "Price": "14.00", "Quantity": 1, "StockStatus": "instock", "StockMessage": "In Stock", "WarrantyItem": null, "Description": "Coral/Blue Embellished Two In One Dress (3mths-7yrs)", "Url": "/g82272s2", "FulfilmentType": ""}, {"ItemID": 2, "ItemNumber": "912767", "OptionNo": "13", "SizeDescription": "11 EU 29", "Price": "16.00", "Quantity": 1, "StockStatus": "instock", "StockMessage": "In Stock", "WarrantyItem": null, "Description": "Silver Buckle Corkbed Sandals (Younger)", "Url": "/g82272s2", "CustomItemFields": [], "FulfilmentType": ""}] console.log(keep(keepThese, orig))
 <script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Docs: _.map() , _.pick()文档: _.map() , _.pick()


The following keep function will do this, although there might be a more elegant way using lodash , for example.下面的keep函数将执行此操作,尽管例如使用lodash可能有更优雅的方法。

 const keep = (k, l) => l.map(o => Object.entries(o).reduce((r, [n, v]) => k.includes(n) ? (r[n] = v, r) : r, {})) const keepThese = ["ItemID", "ItemNumber", "OptionNo", "Quantity", "Price", "Description", "StockStatus", "Url"] const orig = [{"ItemID": 1, "ItemNumber": "611741", "OptionNo": "22", "SizeDescription": "3-6 Mths", "Price": "14.00", "Quantity": 1, "StockStatus": "instock", "StockMessage": "In Stock", "WarrantyItem": null, "Description": "Coral/Blue Embellished Two In One Dress (3mths-7yrs)", "Url": "/g82272s2", "FulfilmentType": ""}, {"ItemID": 2, "ItemNumber": "912767", "OptionNo": "13", "SizeDescription": "11 EU 29", "Price": "16.00", "Quantity": 1, "StockStatus": "instock", "StockMessage": "In Stock", "WarrantyItem": null, "Description": "Silver Buckle Corkbed Sandals (Younger)", "Url": "/g82272s2", "CustomItemFields": [], "FulfilmentType": ""}] console.log(keep(keepThese, orig))

Explanation : .map() the input to Object.entries() .reduce() 'd to an Object , starting from {} .说明.map()输入到Object.entries() .reduce()到一个Object ,从{}开始。
So (r, [n, v]) => k.includes(n) ? (r[n] = v, r) : r所以(r, [n, v]) => k.includes(n) ? (r[n] = v, r) : r (r, [n, v]) => k.includes(n) ? (r[n] = v, r) : r runs for each property in each object in the array. (r, [n, v]) => k.includes(n) ? (r[n] = v, r) : r为数组中每个对象的每个属性运行。 If the array of properties to keep .includes() the current property's name, add the corresponding property & value to r .如果属性数组要保留.includes()当前属性的名称,则将相应的属性 & 值添加到r Otherwise don't touch r .否则不要触摸r Repeat for next property, at the end add r to result array.对下一个属性重复,最后将r添加到结果数组中。

I recommend you study the use of map() and filter() and even find() .我建议你学习map()filter()甚至find()

See the documentation for using Map and Filter or Find .请参阅有关使用MapFilterFind的文档。

With them you can perform various validations and transformations on objects in your array.使用它们,您可以对数组中的对象执行各种验证和转换。

And to exclude a key with the value of an object you will need:并排除具有对象值的键,您将需要:

delete myObject.regex;
// or,
delete myObject['regex'];
// or,
var prop = "regex";
delete myObject[prop];

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM