在自定义函数中删除属性后构造新对象?

时间:2018-04-13 02:51:09

标签: javascript

我正在努力应对挑战问题,我认为我几乎已经解决了。我的第一个问题是输入数据的格式,即优惠券,似乎是csv,而不是json。我知道D3可以轻松转换,但我也习惯与json合作,想到了解决方案。

输入数据的外观(可能是csv):https://imgur.com/a/2dvCt

第二个问题是我不确定如何构造一个新的对象数组来删除每个对象上的属性。在这种情况下,我想删除对象上的代码属性。我将举例说明一个对象的样子:

const exData = [{
"upc":"9131891630585208",
"code":"30417547581177009338",
"category":"Gift Cards",
"itemPrice":"19.82",
"couponAmount":"2.74"  
}]

function personalizedList(coupons, preferredCategories) {
      const filteredByCategory = coupons.filter( coupon =>   
                                  coupon.category === preferredCategories);
      const sorted = filteredByCategory.sort( 
                            (a,b) => b.couponAmount - a.couponAmount );
      const topTen = sorted.slice(0,9);

      //help here. Thinking about using forEach to construct a new obj 
      //but I want to remove one of the properties in my output, aka 
     // something like delete coupon.code on each object in my topTen
}

1 个答案:

答案 0 :(得分:2)

您可以合并forEachdelete以最有效的方式执行此操作:

// Build an array of objects, some with a `bam` key that we want to remove
arrayOfStuff = [{ foo: 'keep this', bam: 'remove this' }, { foo: 'keep this' }]

// Delete anything with a `bam` key in the array of objects
arrayOfStuff.forEach(i => delete i.bam)

// Return completed array
arrayOfStuff

这些操作的输出如下所示:

[
  { foo: 'keep this' },
  { foo: 'keep this' }
]

我认为你在追求什么?