How to merge merge multiple array to single array in javascript - javascript

I have multiple array in which there are multiple types of data such as:
var student= [{
id : 1,
name : 'name1',
year: 2016,
dist_id: 251,
zone_id: 25106
},
{
id : 1,
name : 'name2',
year: 2018,
dist_id: 252,
zone_id: 25212
},];
var dist= [{
id : 251,
name : 'dist1'
},
{
id : 252,
name : 'dist2'
}];
var zone= [{
id : 25106,
name : 'zone1'
},
{
id : 25212,
name : 'zone2'
}];
I want to create an array that combines all the data into one, so that the fields in the array look like this:
var merge = [{
id: 1,
name : 'name1',
year: 2016,
distname : 'dist1',
zonename: 'zone1',
},
{
id: 2,
name : 'name2',
year: 2018,
distname : 'dist2',
zonename: 'zone2',
}];
Thanks in advance.

You could take a Map for distance and zone and map the values in new objects.
var student = [{ id: 1, name: 'name1', year: 2016, dist_id: 251, zone_id: 25106 }, { id: 1, name: 'name2', year: 2018, dist_id: 252, zone_id: 25212 }],
dist = [{ id: 251, name: 'dist1' }, { id: 252, name: 'dist2' }],
zone = [{ id: 25106, name: 'zone1' }, { id: 25212, name: 'zone2' }],
distMap = new Map(dist.map(({ id, name: distname }) => [id, { distname }])),
zoneMap = new Map(zone.map(({ id, name: zonename }) => [id, { zonename }])),
merged = student.map(({ id, name, year, dist_id, zone_id }) => Object.assign(
{ id, name, year },
distMap.get(dist_id),
zoneMap.get(zone_id)
));
console.log(merged);
.as-console-wrapper { max-height: 100% !important; top: 0; }

You could map() the student array to the required merge array where, for each mapping iteration, you would search the dist and zone arrays for items that match on dist_id and zone_id respectively, and merge the name of the into the mapped result:
var student= [
{ id : 1, name : 'name1', year: 2016, dist_id: 251, zone_id: 25106 },
{ id : 1, name : 'name2', year: 2018, dist_id: 252, zone_id: 25212 } ];
var dist= [
{ id : 251, name : 'dist1' }, { id : 252, name : 'dist2' }];
var zone= [
{ id : 25106, name : 'zone1' }, { id : 25212, name : 'zone2' } ];
// Perform a mapping over the student array to aquire merge array in required
// format, with required distname/zonename data
var merge = student.map((s) => {
// Search dist and zone arrays for items that match of dist_id/zone_id
// by filtering and mapping these arrays to find distname and zonename
// for this student
const distname = dist.filter(d => d.id === s.dist_id).map(d => d.name)[0];
const zonename = zone.filter(z => z.id === s.zone_id).map(z => z.name)[0];
return {
id : s.id,
name : s.name,
year : s.year,
distname : distname,
zonename : zonename
}
});
console.log('required merge array:', merge)

Related

Getting syntax error when trying to create dictionary of object

I am getting an array of objects from API like below :
[
{
jobId:100,
jobName: "Java",
cities:[
{
cityId:10,
name : "chicago"
},
{
statusId:11,
name : "miami"
}]
},
{
jobId:101,
jobName: "Python",
cities:[
{
cityId:11,
name : "california"
},
{
cityId:12,
name : "texas"
}]
}
]
I want to access a city name of particular job like below :
var jobId = 101;
var cityId = 12;
var texas = jobDict[jobId].cityDict[cityId] // output: texas
Code:
angular.forEach(response.data, function (data) {
if (jobsDict[data.jobId] == undefined) {
jobsDict[data.jobId] = [];
}
angular.forEach(data.cities, function (city) {
jobsDict[data.jobId].push({
cityDic[city.cityId]: city.name // syntax error here saying unexpected token
});
});
});
I am trying to create a dictionary of jobs and inside a job dictionary, a dictionary of cities.
Can someone please help me fix the issue and achieve the desired output?
Your jobsDict is an array and therefore uses 0-based indexing, not jobID keys.
Likewise for the nested cities.
let jobDict = [{
jobId: 100,
jobName: "Java",
cities: [{
cityId: 10,
name: "chicago"
}, {
statusId: 11,
name: "miami"
}]
}, {
jobId: 101,
jobName: "Python",
cities: [{
cityId: 11,
name: "california"
}, {
cityId: 12,
name: "texas"
}]
}];
let jobId = 101;
let cityId = 12;
let texas =
jobDict.find(job => job.jobId === jobId)
.cities.find(city => city.cityId === cityId)
.name;
console.log(texas);
Following up on your comments, if you're really concerned about performance (which you shouldn't be unless you have 1000's of entries), here's how you can transform the original structure to a 'dictionary' structure that uses the job & city IDs as keys:
let jobs = [{
jobId: 100,
jobName: "Java",
cities: [{
cityId: 10,
name: "chicago"
}, {
cityId: 11,
name: "miami"
}]
}, {
jobId: 101,
jobName: "Python",
cities: [{
cityId: 11,
name: "california"
}, {
cityId: 12,
name: "texas"
}]
}];
let jobsById = Object.fromEntries(jobs.map(({jobId, jobName, cities}) =>
[jobId, {jobName, cities: Object.fromEntries(cities.map(({cityId, name}) => [cityId, name]))}]));
// Equivalent using traditional for loops.
let jobsById2 = {};
for (job of jobs) {
let cities = {};
for (city of job.cities)
cities[city.cityId] = city.name;
jobsById2[job.jobId] = {jobName: job.jobName, cities};
}
console.log(jobsById[101].cities[12]);
console.log(jobsById2[101].cities[12]);
Maybe something like:
const jobArray = [{
jobId: 100,
jobName: "Java",
cities: [{
cityId: 10,
name: "chicago"
},
{
cityId: 11,
name: "miami"
}
]
},
{
jobId: 101,
jobName: "Python",
cities: [{
cityId: 11,
name: "california"
},
{
cityId: 12,
name: "texas"
}
]
}
];
function index_job_array_A(jobArray) {
return jobArray.reduce(
(acc, item) => Object.assign(acc, {
[item.jobId]: Object.assign({}, item, {
cities: item.cities.reduce(
(acc, item) => Object.assign(acc, { [item.cityId]: item }),
{}
)
})
}),
{}
);
};
function index_job_array_B(jobArray) {
let indexed_jobs = {};
jobArray.forEach(function(job) {
let indexed_cities = {};
job.cities.forEach(function(city) {
indexed_cities[city.cityId] = city;
});
indexed_jobs[job.jobId] = { ...job, cities: indexed_cities };
});
return indexed_jobs;
};
const jobDictA = index_job_array_A(jobArray);
const jobDictB = index_job_array_B(jobArray);
console.log(jobDictA['100'].cities['10']);
console.log(jobDictB['100'].cities['10']);

How to add property value from one array of objects into another (for the matching objects) in JS

I am trying to filter array of objects based on another array of objects and after finding all matching items I want to set property and value from the first array object into corresponding object in the second array:
const searchedProducts = products.filter(product =>
uniqueProducts.some(
uniqueProduct =>
product.productId === uniqueProduct.productId,
),
)
After here I need to set product.productName for each unique product object under productName property.
Ho such a thing can be achieved in a better way?
This is probably most straightforward using reduce() combined with find() to both retrieve and verify that the second array contains each object.
const uniqueProducts = [
{id: 3, from: 'uniqueProducts', name: 'Unique 1'},
{id: 12, from: 'uniqueProducts', name: 'Unique 12'}
];
const products = [
{id: 1, from: 'products', name: 'Product 1'},
{id: 2, from: 'products', name: 'Product 2'},
{id: 9, from: 'products', name: 'Product 9'},
{id: 12, from: 'products', name: 'Product 12'},
];
const output = products.reduce((a, p) => {
const uP = uniqueProducts.find(u => u.id === p.id);
if (uP) a.push({...p, name: uP.name});
return a;
}, []);
console.log(output);
I have inventory where I have to add a price property and take its value from products array so I did this,
inventory = [
{
"productId": 1,
"quantity": 100,
"name": "2 Yolks Noodles",
"image": "twoeggnoodles.jpg",
}
]
Products = [
{
"id": 1,
"quantity": 100,
"name": "2 Yolks Noodles",
"image": "twoeggnoodles.jpg",
"price": 34.95
}
]
let product:any = [];
products.map((prod:any)=>{
const index:any = inventory.find((u:any) => u.productId === prod.id);
// console.log("item", index, '-', prod)
if(index){
product.push({...index, price: prod.price});
}
return prod
})
});

JS - merge object same array lodash

I need to transform a array of multiple object in one array object,
I explain myself, I wish to group for each table the objects that carry the same "month" and replace the properties that have the same value by adding their ID at the beginning:
ex:
quantity: 1
becomes fpsIssuedQuantity (in camelCase). http://jsfiddle.net/rLjQx/96589/
here are my data :
var data = {
"2018-01": [
{ id:"fpsIssued", month:"2018-01", quantity:"28" },
{ id:"dgfipIncome", month:"2018-01", amount:1350 },
{ id:"antaiPaidFps", month:"2018-01", quantity:2242 }
],
"2018-02": [
{ id: "fpsIssued", month: "2018-02", quantity: "29" },
{ id: "dgfipIncome", month: "2018-02", amount: 8530 },
{ id: "antaiPaidFps", month: "2018-02", quantity: 4857}
]
};
console.log(data);
and the expected data :
var expectedData = {
"2018-01": [
{ month: "2018-01", fpsIssuedquantity: "28",
dgfipIncomeamount: 1350, antaiPaidFpsQuantity: 2242
}
],
"2018-02": [
{ month: "2018-02", fpsIssuedquantity: "29",
dgfipIncomeamount: 8530, antaiPaidFpsQuantity: 4857
}
]
};
console.log(expectedData);
i use lodash and angularjs but i can not get my result .. please could you help me?
You could map new objects with wanted new property names and values in new objects.
var data = { "2018-01": [{ id: "fpsIssued", month: "2018-01", quantity: "28" }, { id: "dgfipIncome", month: "2018-01", amount: 1350 }, { id: "antaiPaidFps", month: "2018-01", quantity: 2242 }], "2018-02": [{ id: "fpsIssued", month: "2018-02", quantity: "29" }, { id: "dgfipIncome", month: "2018-02", amount: 8530 }, { id: "antaiPaidFps", month: "2018-02", quantity: 4857 }] },
result = Object.assign(
...Object
.entries(data)
.map(
([k, v]) => ({ [k]: Object.assign(...v.map(o => ({ month: o.month, [o.id + ('quantity' in o ? 'Quantity' : 'Amount')]: 'quantity' in o ? o.quantity : o.amount }))) })
)
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Iterate over a list of objects on condition of a another array in jquery

I have a list of object below
the newlist is also dynamic and SelectID array is also dynamic
I am populating thorugh a function , now I have to iteratte and create the new list
var newList =
[
{ id : 1,name="tea",plant:"darjeeling"},
{ id : 2,name="coffee",plant:"manipur"},
{ id : 3,name="milk",plant:"nilgiri"},
{ id : 4,name="tea",plant:"assam"}
]
anaother array which has ID in common
var selectedID = [2,3];
now I have to iterate over the list of objects and update the list of objects as
wherever the ID is 2 and 3 plant should be "munnar "
so how to create new list of objects "newlist" like below
var newList =
[
{ id : 1,name="tea",plant:"darjeeling"},
{ id : 2,name="coffee",plant:"munnar"},
{ id : 3,name="milk",plant:"munnar"},
{ id : 4,name="tea",plant:"assam"}
]
I'm assuming that you are doing this in javascript, so first I want to point out you should have newList defined like this
var newList =
[
{ id : 1,name:"tea",plant:"darjeeling"},
{ id : 2,name:"coffee",plant:"manipur"},
{ id : 3,name:"milk",plant:"nilgiri"},
{ id : 4,name:"tea",plant:"assam"}
]
name="tea" won't work.
But onto your problem, you'll want to use the selectedID array values to update your existing newList like so.
var newList =
[
{ id : 1,name:"tea",plant:"darjeeling"},
{ id : 2,name:"coffee",plant:"manipur"},
{ id : 3,name:"milk",plant:"nilgiri"},
{ id : 4,name:"tea",plant:"assam"}
]
var selectedID =[2,3]
for(i=0;i<newList.length;i++){
for(j=0;j < selectedID.length;j++){
if(newList[i].id==selectedID[j])
newList[i].plant = "munnar";
}
}
console.log(newList);
You could iterate the wanted id for changing, find the object and change the value.
Using:
Array#forEach
Array#find
and a default object {}, if no object is found.
var newList = [{ id: 1, name: "tea", plant: "darjeeling" }, { id: 2, name: "coffee", plant: "manipur" }, { id: 3, name: "milk", plant: "nilgiri" }, { id: 4, name: "tea", plant: "assam" }],
selectedID = [2, 3];
selectedID.forEach(id => (newList.find(a => a.id === id) || {}).plant = 'munnar');
console.log(newList);
.as-console-wrapper { max-height: 100% !important; top: 0; }
From what I understand you wish to manipulate the original array with different values based on an array of selected ids. If those selected ID's which could come from the UI match any of the ids in your array of plants then change the name to Munnar? If I have understood correctly then I believe the following should work for you
var newList = [{
id: 1,
name: "tea",
plant: "darjeeling"
}, {
id: 2,
name: "coffee",
plant: "manipur"
}, {
id: 3,
name: "milk",
plant: "nilgiri"
}, {
id: 4,
name: "tea",
plant: "assam"
}]
function munnar(selectedID) {
newList.forEach( (item) => {
selectedID.forEach( (id) => {
if(item.id === id) {
item.plant = 'Munnar'
}
})
})
}
munnar([2, 3])
This returns
[{
id: 1,
name: "tea",
plant: "darjeeling"
}, {
id: 2,
name: "coffee",
plant: "Munnar"
}, {
id: 3,
name: "milk",
plant: "Munnar"
}, {
id: 4,
name: "tea",
plant: "assam"
}]

Get missing objects from 2 arrays of objects

let selected = [
{id: 15, name: 'Canada'},
{id: 25, name: 'Germany'}
];
let all = [
{id: 15, name: 'Canada'},
{id: 25, name: 'Germany'},
{id: 32, name: 'United States'},
{id: 40, name: 'China'}
]
How do I get non-selected countries from all objects and print it out in another variable? Based on id key of those which are in selected array?
You need to find all objects that aren't contained in selected and then do something with them:
let nonSelectedItems = all.filter(obj => selected.every(s => s.id !== obj.id));
//do stuff with non-selected items
You can use filter and find, so as soon as element with same id is found in selected it will filter out that element from all. You can also use some instead of find.
let selected = [
{id: 15, name: 'Canada'},
{id: 25, name: 'Germany'}
];
let all = [
{id: 15, name: 'Canada'},
{id: 25, name: 'Germany'},
{id: 32, name: 'United States'},
{id: 40, name: 'China'}
]
var r = all.filter(e => !selected.find(a => e.id === a.id));
console.log(r)
Generate an object which holds id as a property using Array#reduce method(which helps to speed up since you need to iterate over and over) and use Array#filter method to filter elements from all array.
// generate the object reference
let ref = selected.reduce(function(obj, o) {
// define property
obj[o.id] = true;
// return object property
return obj;
// set initial value as an object
}, {});
// filter out array elements
let res = all.filter(function(o) {
return !ref[o.id]
})
let selected = [{
id: 15,
name: 'Canada'
}, {
id: 25,
name: 'Germany'
}];
let all = [{
id: 15,
name: 'Canada'
}, {
id: 25,
name: 'Germany'
}, {
id: 32,
name: 'United States'
}, {
id: 40,
name: 'China'
}]
let ref = selected.reduce(function(obj, o) {
obj[o.id] = true;
return obj;
}, {});
console.log(
all.filter(function(o) {
return !ref[o.id]
})
)
With ES6 arrow function :
let ref = selected.reduce((obj, o) => (obj[o.id] = true, obj), {});
let res = all.filter(o => !ref[o.id]);
let selected = [{
id: 15,
name: 'Canada'
}, {
id: 25,
name: 'Germany'
}];
let all = [{
id: 15,
name: 'Canada'
}, {
id: 25,
name: 'Germany'
}, {
id: 32,
name: 'United States'
}, {
id: 40,
name: 'China'
}]
let ref = selected.reduce((obj, o) => (obj[o.id] = true, obj), {});
console.log(
all.filter(o => !ref[o.id])
)

Categories

Resources