猿问

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

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},

    ]


回首忆惘然
浏览 255回答 1
1回答

收到一只叮咚

你可以使用lodash filter。它将允许您挑选出数组中满足条件的所有对象。import filter from 'lodash/filter'const array = [&nbsp; &nbsp; &nbsp; &nbsp; {id:1,country: "India", city:"city1", year:2019, jan:220, feb:300},&nbsp; &nbsp; &nbsp; &nbsp; {id:2,country: "India", city:"city1", year:2019, jan:777, feb:555},&nbsp; &nbsp; &nbsp; &nbsp; {id:3,country: "UK", city:"city2", year:2019, jan:1, feb:12},&nbsp; &nbsp; &nbsp;]// gives you a list of all objects that match you conditions.const filteredArray = filter(array, {country: "India", city: "city1"})&nbsp;// 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 objectsarray.push(newObject)希望能给你一个开始的地方。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答