简体   繁体   中英

I have an array of multiple objects. Can we create new object based on conditions?

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

I have an array of multiple objects.

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

Can we create new object based on conditions for eg: if country matches and city matches then some "Divide" calculation for Jan and Feb and we can have 3rd object?

Any Suggestion and help will be appreciated.

[
    {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},
    ]

You could use lodash filter .

It will allow you to pick out all of the objects in the array that meet the condition.

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)

Hope that gives you somewhere to start.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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