为了账号安全,请及时绑定邮箱和手机立即绑定

我有一个包含多个对象的数组。我们可以根据条件创建新对象吗?

我有一个包含多个对象的数组。我们可以根据条件创建新对象吗?

回首忆惘然 2021-10-07 20:21:25
var arrNewMarket=[];var arrMarket=[{id:1,country:"India",city:"city1",fruit:"Red Apple",year:2019,jan:220,feb:300},{id:2,country:"India",city:"city1",fruit:"Green Apple",year:2019,jan:777,feb:555},  {id:3,country:"India",city:"city2",fruit:"Red Apple",year:2019,jan:333,feb:888},]console.log(arrMarket);for (let i = 0; i < arrMarket.length-1; i++) {  for (let j = i+1; j < arrMarket.length; j++)   {     if(arrMarket[i].country==arrMarket[j].country && arrMarket[i].city==arrMarket[j].city) {       arrNewMarket.push({         id:4,         country:arrMarket[i].country,         city:arrMarket[i].city,         fruit:"Apple",         year:arrMarket[i].year,         jan:arrMarket[i].jan/arrMarket[j].jan,         feb:arrMarket[i].feb/arrMarket[j].feb,       });     }  }}我有一个包含多个对象的数组。var arrMarket=[];[{id:1,country:India,city:city1,year:2019,jan:220,feb:300},{id:2,country:India,city:city1,year:2019,jan:777,feb:555},]我们可以根据条件创建新对象,例如:如果国家匹配且城市匹配,那么一月和二月的一些“划分”计算,我们可以有第三个对象吗?任何建议和帮助将不胜感激。[    {id:1,country:India,city:city1,year:2019,jan:220,feb:300},    {id:2,country:India,city:city1,year:2019,jan:777,feb:555}, {id:3,country:India,city:city1,year:2019,jan:0.28,feb:0.54},    ]
查看完整描述

1 回答

?
收到一只叮咚

TA贡献1821条经验 获得超4个赞

你可以使用lodash filter。


它将允许您挑选出数组中满足条件的所有对象。


import filter from 'lodash/filter'


const array = [

        {id:1,country: "India", city:"city1", year:2019, jan:220, feb:300},

        {id:2,country: "India", city:"city1", year:2019, jan:777, feb:555},

        {id:3,country: "UK", city:"city2", year:2019, jan:1, feb:12},

     ]


// gives you a list of all objects that match you conditions.

const filteredArray = filter(array, {country: "India", city: "city1"}) 


// make a new object with whatever math you wanted to do.

const newObject = {id: array.length, country: "India", city: "city1", year: 2019, jan: filteredArray.map(**some calculation**),feb: filteredArray.map(**some calculation**)}


// to ad it back to the original array of objects

array.push(newObject)

希望能给你一个开始的地方。


查看完整回答
反对 回复 2021-10-07
  • 1 回答
  • 0 关注
  • 254 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信