var data = [
{ extn: '2014', agentid: 'sravya', comments: '' },
{ extn: '2015', agentid: 'shalini', comments: '' }
]
const localityParameterSets = data.map(function(value){
return [
{name:"extn",value:{stringValue:value['extn']}},
{name:"agentid",value:{stringValue:value['agentid']}},
{name:"comments",value:{stringValue:value['comments']}}
]
})
console.log(JSON.stringify(localityParameterSets))
The above code is working fine but I need to make this name and value dynamically without hardcode i.e key value
for example "extn" string is hardcoded instead key value should come
"agentid" string is hardcoded instead key value should come
Use Object.entries and build the object dynamically.
var data = [
{
extn: '2014',
agentid: 'sravya',
comments: ''
},
{
extn: '2015',
agentid: 'shalini',
comments: ''
}
]
const localityParameterSets = data.map(function(value) {
return Object.entries(value).map( ([key,val]) => ({name:key, value:{stringValue:val}}))
})
console.log(localityParameterSets)
You could get the entries and map objects.
const
data = [{ extn: '2014', agentid: 'sravya', comments: '' }, { extn: '2015', agentid: 'shalini', comments: '' }],
result = data.map(o => Object.entries(o).map(([name, value]) => ({ name, value })));
console.log(result);
Related
I'm trying to create a String based upon an object consisting of several key-value pairs.
Example:
[{ name: 'cookie1', value: 'false' },
{ name: 'cookie2', value: '123' },
{ name: 'cookie3',value: 'abc'}]
What I'm trying to achieve (string):
cookie1: false, cookie2: 123, cookie3: abc
I've tried to extract just the val using map like this (played around moving around values):
var output = cookies.map(d => {
return {
"name": d.name,
"value": d.value,
}
})
One way to do this is to map the array of objects into name: value strings and then join them with , :
const data = [{ name: 'cookie1', value: 'false' },
{ name: 'cookie2', value: '123' },
{ name: 'cookie3',value: 'abc'}]
const result = data.map(({ name, value }) => `${name}: ${value}`).join(', ')
console.log(result)
I am trying to reshape some data to be used in a table. To do this I am mapping over an array and then looping over an object inside of it to create a new object with the data I want in it. The issue Im having is if the object contains more than one object inside of it I only get a new object for the first item.
I am trying to get a new object for each of the objects held inside changedProperties
Can anyone help? / Explain?
Here is a working example:
const MOCK_DATA = [
{
triggeredByID: "d5ae18b7eb6f",
triggeredByName: "name",
changedProperties: {
LastName: {
__oldValue: "Mallory",
__newValue: "Mallorie",
},
Suffix: {
__oldValue: "DO",
__newvValue: "NP",
},
},
createdAt: "2022-06-01T10:20:21.329337652Z",
},
{
triggeredByID: "d5ae18b7eb6f",
triggeredByName: "John",
changedProperties: {
State: {
__oldValue: ["TX", "AL"],
__newValue: ["TX", "AL", "FL"],
},
City: {
__oldValue: "Austin",
__newValue: "San Antonio",
},
},
createdAt: "2022-06-01T10:20:21.329337652Z",
},
];
const changedProperties = MOCK_DATA.map((item, idx) => {
for (const [key, value] of Object.entries(item.changedProperties)) {
return {
field: key,
old: item.changedProperties[key].__oldValue,
new: item.changedProperties[key].__newValue,
name: item.triggeredByName,
createdAt: item.createdAt,
};
}
});
console.log(changedProperties)
Yes, if you return inside a for-loop, its scoped to the function. Meaning you will return from the entire function on the first iteration of your loop. Try this instead:
const changedProperties = MOCK_DATA.map((item, idx) => {
return Object.entries(item.changedProperties).map(([key, value]) => {
return {
field: key,
old: item.changedProperties[key].__oldValue,
new: item.changedProperties[key].__newValue,
name: item.triggeredByName,
createdAt: item.createdAt,
};
}
});
console.log(changedProperties)
How can i sort and rearrange an array that looks like this
fields = [
{
uid: '2c2162cc-37d0-f1e3-96c2-6d9ccb50f38d',
field: new ObjectId("627f816d8443318c6aaa1220"
},
{
uid: '2aa60f96-135b-e179-2b46-516c87a877cc',
field: new ObjectId("6283cb3ca573a56e11587c46"),
}
]
to match the arrangement of this array:
order = [ '6283cb3ca573a56e11587c46', '627f816d8443318c6aaa1220' ]
Here is the output I’m looking for:
[
{
uid: '2aa60f96-135b-e179-2b46-516c87a877cc',
field: new ObjectId("6283cb3ca573a56e11587c46"),
},
{
uid: '2c2162cc-37d0-f1e3-96c2-6d9ccb50f38d',
field: new ObjectId("627f816d8443318c6aaa1220"),
}
]
findIndex and sort but I am very confused
fields.sort((a: any, b: any) => order.indexOf(a.field) - order.indexOf(b.field)) // It does not work
You need to use sort method on the array. And then compare the index of field on the order array.
const data = [
{
uid: '2aa60f96-135b-e179-2b46-516c87a877cc',
field: "6283cb3ca573a56e11587c46",
value: 'test val 6'
},
{
uid: '2c2162cc-37d0-f1e3-96c2-6d9ccb50f38d',
field: "627f816d8443318c6aaa1220",
value: ''
}
]
const order = [ '6283cb3ca573a56e11587c46', '627f816d8443318c6aaa1220' ];
data.sort((a,b) => order.indexOf(a.field) - order.indexOf(b.field));
console.log(data);
Notice: ObjectId class is not defined here, so I changed it to string here for simplicity.
I have 100 objects of data within an array that looks like this:
{
id: "1",
date: "2022/01/01",
name: "John",
},
{
id: "2",
date: "2022/01/02",
name: "Chris",
},
I am trying to return an array of objects by date that also returns the names.
For example:
[
{
date: "2022/01/01",
names: ["John", "Steve"...]
},
{
date: "2022/01/02",
names: ["Chris", "Rob"...]
},
]
I have tried using the reduce method:
const groupedByDate = () =>
data.reduce((itemsIterated, { date, name }) => {
if (!itemsIterated[date]) {
itemsIterated[date] = {
date,
names: [],
};
}
itemsIterated[date].names.push(name);
return itemsIterated;
}, []);
The issue is this gives me array with a key of the date and then the object with date/names but I don't know how to return just the array of objects by date.
The function groupedByDate would return an object like this -
const result = {
'2022/01/01': {
date: "2022/01/01",
names: ["John", "Steve"...]
},
'2022/01/02': {
date: "2022/01/02",
names: ["Chris", "Rob"...]
},
}
However, to retrieve it in the format you need, you would need to make use of Object.values().
Object.values(result);
/*
[
{
date: "2022/01/01",
names: ["John", "Steve"...]
},
{
date: "2022/01/02",
names: ["Chris", "Rob"...]
},
]
*/
NOTE
To learn more about Object.values() - MDN
reduce's second parameter is the initial value of the accumulator. Here, we would need to use {} instead of [] in the groupedByDate function.
It works except when the subject unless the subject is the same name. Then I get the first date to the second subject that is the same.
I can't change the array since it's through API. However can I make so somehow if the first date is already set on math, then it should add the second date to second subject? Now the second subject get's the first date
var subjects = [
{ name: "math" }, //The first
{ name: "sports" },
{ name: "math" }, //The second
{ name: "art" },
];
var subjectdates = [
{ name: "math", year: 2017 }, //first date
{ name: "sports", year: 2018 },
{ name: "math", year: 2019 }, //second date
{ name: "art", year: 2020 },
];
const addDates = subjects.map((classes) => ({
subject: classes,
end_subject_date: subjectdates.find((item) => classes.name == item.name),
}));
console.log(addDates);
Using Array#reduce on subjectdates, construct a Map where the key is the name and the value is a list of the elements of this name.
Then, in the loop, to get the end_subject_date, you can use Map#get to get the list of elements of this name, and Array#shift to get and remove the first element:
const
subjects = [ {name:"math"}, {name:"sports"}, {name:"math"}, {name:"art"} ],
subjectdates = [ {name:"math",year:2017}, {name:"sports",year:2018}, {name:"math",year:2019}, {name:"art",year:2020} ];
const subjectDatesMap = subjectdates.reduce((map, item) =>
map.set(
item.name,
[...(map.get(item.name) || []), item]
)
, new Map);
const addDates = subjects.map(classes => ({
subject: classes,
end_subject_date: (subjectDatesMap.get(classes.name) || []).shift()
}));
console.log(addDates);
If you have the same keys in arrays:
Sort array by keys:
subjects = subjects.sort((a,b)=>a.name>b.name?1:-1);
subjectdates = subjectdates.sort((a,b)=>a.name>b.name?1:-1);
Insert values by index:
const result = subjects.map((s, i)=>
({ subject:s.name, end_subject_date:subjectdates[i].year}) );