Facing issue with Javascript array - javascript

I am getting an array of object data from service as below:
outputs
array= [
{id:1,Name:GHI,Gender:Male,DOB:12/1/2020},
{id:1,Name:GHI,Gender:Female,DOB:10/1/2020},
{id:2,Name:ABC,Gender:Male,DOB:02/02/2020},
{id:2,Name:ABC,Gender:Female,DOB:03/04/2019},
{id:3,Name:EFG,Gender:Male,DOB:09/09/2010},
{id:3,Name:EFG,Gender:Female,DOB:08/07/2021}
]
I have applied group by function and mapping by using the key
let key="id";
const groupBy=(array,key)=>{
return Object.entries(array.reduce((result,currentvalue)=>{
(result[currentValues[key]]=result[currentValue[key]]||[]).push(
currentvalue
);
return result;
},{})).map(v=>({[key]:v[0],data:v[1]})));
};
I am able to get data like this
[
{
Id:1,
data:
[
{id:1,Name:GHI,Gender:Male,DOB:12/1/2020},
{id:1,Name:GHI,Gender:Female,DOB:10/1/2020}
]
},
{
Id:2,
data:
[
{id:2,Name:ABC,Gender:Male,DOB:02/02/2020},
{id:2,Name:ABC,Gender:Female,DOB:03/04/3019}
]
}...
]
But I need the out put some thing like this I need to group by Id but need the Name of Id something like this
[
{
Name:GHI,
data:[
{id:1,Name:GHI,Gender:Male,DOB:12/1/2020},
{id:1,Name:GHI,Gender:Female,DOB:10/01/2020}
]
},
{
Name:ABC,
data:[
{id:2,Name:ABC,Gender:Male,DOB:02/02/2020},
{id:2,Name:ABC,Gender:Female,DOB:03/04/2019}
]
},
{
Name:EFG,
data:[
{id:3,Name:EFG,Gender:Male,DOB:09/09/2010},
{id:3,Name:EFG,Gender:Male,DOB:08/07/2021}
]
}
]
Please let me know how to retrieve data in expected format to display on UI.

try with the below code.
var arr = [
{id:1,Name:"GHI",Gender:"Male",DOB:"12/1/2020"},
{id:1,Name:"GHI",Gender:"Female",DOB:"10/1/2020"},
{id:2,Name:"ABC",Gender:"Male",DOB:"02/02/2020"},
{id:2,Name:"ABC",Gender:"Female",DOB:"03/04/2019"},
{id:3,Name:"EFG",Gender:"Male",DOB:"09/09/2010"},
{id:3,Name:"EFG",Gender:"Female",DOB:"08/07/2021"}
]
let temp = {}
arr.forEach((obj) => {
temp[obj.Name] = temp[obj.Name] || [];
temp[obj.Name].push(obj);
});
let output = Object.entries(temp).map(obj => {
return {"Name": obj[0], "data": obj[1]}
});
console.log(JSON.stringify(output, null, 2));

You may go simpler and more readable:
let result = {};
for (const data of array) {
const { Name } = data;
if (!result[Name]) {
result[Name] = { Name, data: [data] };
} else {
result[Name].data.push(data);
}
}

Related

How to filter array and create new array with specific object keys

I have an array with objects and in each object there is an "items" array. My goal is to combine these "items" into one array.
Goal / Expected Output
[
{ id: 'SUV' },
{ id: 'Compact' },
{ id: 'Gasoline' },
{ id: 'Hybrid' }
]
Sample Array
[
{
"id":"carType",
"items":[
{
"id":"SUV"
},
{
"id":"Compact"
}
]
},
{
"id":"fuelType",
"items":[
{
"id":"Gasoline"
},
{
"id":"Hybrid"
}
]
}
]
You could use Array#flatMap.
const data = [{"id":"carType","items":[{"id":"SUV"},{"id":"Compact"}]},{"id":"fuelType","items":[{"id":"Gasoline"},{"id":"Hybrid"}]}];
const r = data.flatMap(({ items }) => items);
console.log(r);
A one-liner in vanilla JS (earlier than EMCAScript 2019, flatMap is not available, so in case of that...)
[].concat(...arr.map(elt => elt.items))
Something like this?
newArr = []
for (let i = 0;i<arr.length;i++) {
for (let ii = 0;ii<arr[i].items.length;ii++) {
newArr.push(arr[i].items[ii].id)
}
}
console.log(newArr)

Group and merge similar javascript objects

I have the following data and I am stuck between a logic
[
{
"user.employeeId": "10081",
"objectives": [
"Improve consultation"
],
"param": "dueByDays"
},
{
"user.employeeId": "10081",
"objectives": [
"Building a strong team"
],
"param": "overdue"
},
]
How can I get the data in the below format, I have tried Map(), ForEach(), etc. but I am getting stuck,
This is the requirement/Output
[
{
'user.employeeId': '10081',
params: [
{
objectives: ['Improve consultation'],
param: 'dueByDays'
},
{
objectives: ['Building a strong team'],
param: 'overdue'
},
{
objectives: null,
param: 'dueToday'
}
]
}];
If suppose param is not available, we still need to set objective as null, please help me out regarding this query. It would be better if anyone can help me do this using lodash
There will be only 3 params as mentioned above
The approach here would be something like this:
create some "storage" object (can be a simple object);
iterate through items;
if this is a new employee, then create new record in the "storage";
if this is a known employee, just update its info.
After this, the storage object has to be converted to an array, as per requirement:
const userEntries = /* initial array */;
const tempStorage = Object.create(null); // or just '{}'
for (const entry of userEntries) {
const id = entry["user.employeeId"];
const param = {
objectives: entry.objectives,
param: entry.param,
};
if (id in tempStorage === false) { // this is a new employee
tempStorage[id] = [ param ];
} else { // this is a known employee, it exists in storage
tempStorage[id].push(param);
}
}
// All the necessary data is in tempStorage.
// Now on to converting.
const output = [];
for (const employeeId in tempStorage) {
output.push({
["user.employeeId"]: employeeId,
params: tempStorage[employeeId],
});
}
Something like this should work:
const employeesData = {};
for (let item of array) {
const id = item["user.employeeId"];
if (!employeesData[id]) {
employeesData[id] = {};
}
employeesData[id][item.param] = item.objectives;
}
const params = ['dueByDays', 'overdue', 'dueToday'];
const result = [];
for (let key of Object.keys(employeesData)) {
result.push({
'user.employeeId': key,
params: params.map(param => ({
param,
objectives: employeesData[key][param] || null,
})),
});
}
We first build an object containing all the data then we iterate through the keys to build a proper array.
I don't test it but it should work.
const usersHash = users.reduce((acc, curr) => {
if(acc[curr["user.employeeId"]])
acc[curr["user.employeeId"]].params.push(curr.param ? {...curr.param} : {})
else
acc[curr["user.employeeId"]] = { "user.employeeId": curr["user.employeeId"], params: [{...curr.param}] }
return acc;
},{})
const mergedUsers = Object.values(usersHash);
You can use .reduce() method. The following code should work.
const arr = [
{
"user.employeeId": "10081",
"objectives": [
"Improve consultation"
],
"param": "dueByDays"
},
{
"user.employeeId": "10081",
"objectives": [
"Building a strong team"
],
"param": "overdue"
},
{
"user.employeeId": "10081",
"objectives": [
"A team"
],
},
]
const result = arr.reduce((accumulator, currentValue) => {
const element = accumulator.find(item => item['user.employeeId'] === currentValue['user.employeeId'])
if (element) {
element.params.push({objectives: currentValue.objectives, param: currentValue.param || null})
} else {
accumulator.push({'user.employeeId': currentValue['user.employeeId'], params: [{objectives: currentValue.objectives, param: currentValue.param || null}]})
}
return accumulator
},[])
console.log(result)

Destructuring array of objects in es6

In es6, how can i simplify the following lines using destructuring?:
const array0 = someArray[0].data;
const array1 = someArray[1].data;
const array2 = someArray[2].data;
Whether using destructuring would actually be a simplification is debatable but this is how it can be done:
const [
{ data: array0 },
{ data: array1 },
{ data: array2 }
] = someArray
Live Example:
const someArray = [
{ data: 1 },
{ data: 2 },
{ data: 3 }
];
const [
{ data: array0 },
{ data: array1 },
{ data: array2 }
] = someArray
console.log(array0, array1, array2);
What is happening is that you're first extracting each object from someArray then destructuring each object by extracting the data property and renaming it:
// these 2 destructuring steps
const [ obj1, obj2, obj3 ] = someArray // step 1
const { data: array0 } = obj1 // step 2
const { data: array1 } = obj2 // step 2
const { data: array2 } = obj3 // step 2
// written together give
const [
{ data: array0 },
{ data: array1 },
{ data: array2 }
] = someArray
Maybe combine destructuring with mapping for (potentially) more readable code:
const [array0, array1, array2] = someArray.map(item => item.data)
Live Example:
const someArray = [
{ data: 1 },
{ data: 2 },
{ data: 3 }
];
const [array0, array1, array2] = someArray.map(item => item.data)
console.log(array0, array1, array2);
I believe what you actually want is
const array = someArray.map(x => x.data)
If you really want three variables (Hint: you shouldn't), you can combine that mapping with destructuring:
const [array0, array1, array2] = someArray.map(x => x.data)
If you want to do with this pure JS then follow this code snippet. It will help you.
let myArray = [
{
"_id": "1",
"subdata": [
{
"subid": "11",
"name": "A"
},
{
"subid": "12",
"name": "B"
}
]
},
{
"_id": "2",
"subdata": [
{
"subid": "12",
"name": "B"
},
{
"subid": "33",
"name": "E"
}
]
}
]
const array = myArray.map(x => x.subdata).flat(1)
const isExist = (key,value, a) => {
return a.find(item => item[key] == value)
}
let a = array.reduce((acc, curr) => {
if(!isExist('subid', curr.subid, acc)) {
acc.push(curr)
}
return acc
}, [])
console.log(a)
const myInfo = someArray.map((item) => {
const {itemval1, itemval2} = item;
return(
//return data how you want it eg:
<p>{itemval1}</p>
<p>{itemval2}</p>)
})
This is how I did it in react, correct me if m wrong, I'm still new to this world
#Daniel, I presume you were looking to destructure a nested Object in an array of Objects. Following #nem035 was able to extract the nested Object's property using his pattern.
What is happening is that you're first extracting each object from addresses array then destructuring each object by extracting its properties and renaming it including the nested Object:
addresses = [
{
locality:"Sarjapura, Bangalore",
coordinates:{latitude:"12.901160", longitude:"77.711680"}
},
{
locality:"Vadakara, Kozhikode",
coordinates:{latitude:"11.588980", longitude:"75.596450"}
}
]
const [
{locality:loc1, coordinates:{latitude:lat1, longitude:ltd1}},
{locality:loc2, coordinates:{latitude:lat2, longitude:ltd2}}
] = addresses
console.log(`Latitude of Vadakara :: ${lat2}`)

How to insert objects through javascript?

I have stored group of objects into one array called 'resData' and i'm having one more array of data called 'approvedIds', there have included all approved id's. Here i want to match these two arrays and add one new key into 'resData' array like 'approveStatus:"approve"'. How to do this one in javascript?
All data's,
var resData = [
{
firstName:"Jhon",
lastName:"adam",
emailId:"jhn12#gmail.com",
id:"01"
},
{
firstName:"Kyle",
lastName:"Miller",
emailId:"kl12#gmail.com",
id:"02"
},
{
firstName:"Jhonathan",
lastName:"adam",
emailId:"jadm12#gmail.com",
id:"03"
},
{
firstName:"Lewis",
lastName:"harber",
emailId:"lewh12#gmail.com",
id:"04"
}
];
Approved id's array,
var approvedIds = ['01', '03'];
My output will be like this,
var resData = [
{
firstName:"Jhon",
lastName:"adam",
emailId:"jhn12#gmail.com",
id:"01",
approveStatus:'approved'
},
{
firstName:"Kyle",
lastName:"Miller",
emailId:"kl12#gmail.com",
id:"02"
},
{
firstName:"Jhonathan",
lastName:"adam",
emailId:"jadm12#gmail.com",
id:"03",
approveStatus:'approved'
},
{
firstName:"Lewis",
lastName:"harber",
emailId:"lewh12#gmail.com",
id:"04"
}
];
You can try this. Use forEach and indexOf functions
var resData = [
{
firstName:"Jhon",
lastName:"adam",
emailId:"jhn12#gmail.com",
id:"01"
},
{
firstName:"Kyle",
lastName:"Miller",
emailId:"kl12#gmail.com",
id:"02"
},
{
firstName:"Jhonathan",
lastName:"adam",
emailId:"jadm12#gmail.com",
id:"03"
},
{
firstName:"Lewis",
lastName:"harber",
emailId:"lewh12#gmail.com",
id:"04"
}
];
var approvedIds = ['01', '03'];
resData.forEach(item => {
if(approvedIds.indexOf(item.id) !== -1){
item.approvedStatus = 'approved';
}
} );
console.log(resData);
Using ES6 array functions, which is more functional and doesn't alter the original objects:
var resData = [
{
firstName:"Jhon",
lastName:"adam",
emailId:"jhn12#gmail.com",
id:"01"
},
{
firstName:"Kyle",
lastName:"Miller",
emailId:"kl12#gmail.com",
id:"02"
},
{
firstName:"Jhonathan",
lastName:"adam",
emailId:"jadm12#gmail.com",
id:"03"
},
{
firstName:"Lewis",
lastName:"harber",
emailId:"lewh12#gmail.com",
id:"04"
}
];
var approvedIds = ['01', '03'];
//Solution:
var newData = resData
.filter(rd => approvedIds.indexOf(rd.id) >= 0)
.map(rd => Object.assign({}, rd, {approvedStatus: "approved"}));
console.log(newData, resData);

Javascript - Restructure array of objects

I currently have an array of objects that looks like this:
[
{
"key":"CES0000000001",
"25568.95655":"29923",
"25568.96078":"31603"
},
{
"key":"CES0000000001",
"25568.96501":"34480",
"25568.96924":"38347"
}
]
I'm trying to figure out the best way to restructure this data to look like this:
[
{
"key":"CES0000000002",
"values": [ [ 25568.95655 , 29923 ] , [ 25568.96078 , 31603 ] ]
},
{
"key":"CES0000000002",
"values": [ [ 25568.96501 , 34480 ] , [ 25568.96924 , 38347 ] ]
}
]
Can anyone provide some advice for this and any good resources for restructuring javascript objects? I'm getting more into visualization using d3.js and data formatting is key.
my solution would be
var arr= [
{
"key":"CES0000000001",
"25568.95655":"29923",
"25568.96078":"31603"
},
{
"25568.96501":"34480",
"25568.96924":"38347"
}
];
var transformed= arr.map(function(obj){
var result= {
key: obj.key,
values: []
}
for (var key in obj) {
if (obj.hasOwnProperty(key) && key !== "key") {
result.values.push([key, obj[key]]);
}
}
return result;
});
console.log(transformed);
This is an old post I see, but I want to share how you could do this with es6 object destructuring and restructuring.
if you have an object...
const obj1 = {
"key":"CES0000000001",
"25568.95655":"29923",
"25568.96078":"31603"
};
you could have:
const restructure = ({key, ...values}) => ({key, Object.entries(values)});
const obj2 = restructure(obj1);
or for the array you could restructure all of them with:
const b = arr.map(({key, ...values}) => ({key, Object.entries(values)}));
or if you are reusing the function...
const b = arr.map(restructure);

Categories