How to get the object only from array in javascript? - javascript

I want to achieve this format. As you can see on the output there's a bracket but I want to get only the '10': ["11/21/2022", "11/25/2022"] or this one.
{
'10': ["11/21/2022", "11/25/2022"]
}
const data = [{
user_id: "10",
dates: ["11/21/2022", "11/25/2022"],
}, ];
const output = data.map(({
user_id,
dates
}) => ({
[user_id]: dates
}));
console.log(output);

You can only do this if the array has just one entry. Otherwise, how would you know which array element to use?
Then just create it directly, map creates an array, not an object:
const [{ user_id, dates }] = data;
const output = {
[user_id]: dates,
};
Live Example:
const data = [
{
user_id: "10",
dates: ["11/21/2022", "11/25/2022"],
},
];
const [{ user_id, dates }] = data;
const output = {
[user_id]: dates,
};
console.log(output);
Or without the initial destructuring:
const output = {
[data[0].user_id]: data[0].dates,
};
Live Example:
const data = [
{
user_id: "10",
dates: ["11/21/2022", "11/25/2022"],
},
];
const output = {
[data[0].user_id]: data[0].dates,
};
console.log(output);

map is returning array again, so if you wanna get only object you can use [0] to access it directly
sth like this :
console.log(output[0]);
or this :
const output = data.map(({
user_id,
dates
}) => ({
[user_id]: dates
}))[0];

Related

How to add special character in array map?

How to add special characters like : to array map ? I want to achieve this.
'10': ["11/21/2022", "11/25/2022"]
this is what I have so far
const data = [{
"user_id": "10",
"dates": ["11/21/2022", "11/25/2022"]
}]
const output = data.map(({
user_id,
dates
}) => [user_id, dates]);
console.log(output);
I'm going to guess that you're looking for an array like this as your result:
[
{
10: ["11/21/2022", "11/25/2022"]
},
// ...possibly others here...
]
If so, return a non-array object from your map call rather than an array:
const output = data.map(({ user_id, dates }) => ({[user_id]: dates}));
// −−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^
Example:
const data = [
{
user_id: "10",
dates: ["11/21/2022", "11/25/2022"],
},
];
const output = data.map(({ user_id, dates }) => ({[user_id]: dates}));
console.log(output);
Note how that uses computed property name syntax to create the property in the object, [user_id]: dates. That creates a property using the value of user_id as the name.
If you just want to console.log to appear in the way you described, this then you just have to access the elements from the array and print them in the way you want.
const data = [{
"user_id": "10",
"dates": ["11/21/2022", "11/25/2022"]
}]
const output = data.map(({
user_id,
dates
}) => [user_id, dates]);
console.log(`'${output[0][0]}': ["${output[0][1][0]}, ${output[0][1][1]}"]`);

JavaScript modify Array of Objects and alter contained data

I am having difficulties formatting some data. Currently, I receive data in the following structure.
[
{
"q1":"5",
"q2":[
"13",
"12",
],
"q3":"test",
}
]
I essentially need to modify this or even create a new object, that takes the following structure.
[
{
id: 1, //q1
answers: [
{
answer: '5',
},
],
},
{
id: 2, //q2
answers: [
{
answer: '13',
},
{
answer: '12',
},
],
},
{
id: 3, //q3
answers: [
{
answer: 'test',
},
],
},
];
So the id in the above would be obtained by remove the q and getting the number in the first data object. It would then have an answers array that would have an object for each answer.
I have been attempting this but have gotten lost. I don't know if I should use loops, mapping, filters etc. To be honest, the furthest I have got so far is obtaining the keys
var modified = data.map(function(item) {
return Object.keys(item)
})
I have created a JSFiddle where I have been attempting to do this.
Is there any way I can achieve the data I am after?
Many thanks
Please use map function.
const data = {
"q1":"5",
"q2":[
"13",
"12",
],
"q3":"test",
};
const result = Object.keys(data).map(key => {
let item = {id: key.substring(1), answers: []};
if(typeof data[key] === "string")
item.answers.push({answer: data[key]});
else
item.answers = data[key].map(val => ({answer: val}));
return item;
});
console.log(result)
const inputData = [
{
"q1":"5",
"q2":[
"13",
"12",
],
"q3":"test",
}
]
function answerMapper(objVal, id){
return Array.isArray(objVal)
?
{ id, answers: objVal.map(answer => ({ answer }))}
:
{ id, answers: [{answer: objVal }] }
}
function formatObject(obj){
return Object.keys(obj).map((k, i) => answerMapper(obj[k], i+1));
}
const result = inputData.map(obj => formatObject(obj));
// remove flatMap if your inputData has more than one entry
console.log(result.flatMap(x => x));
map over the first element of the data with Object.entries, grab the key and value, create a new answers array and return a new object.
const data = [{
"q1": "5",
"q2": [
"13",
"12",
],
"q3": "test",
}];
const out = Object.entries(data[0]).map(obj => {
const [ key, value ] = obj;
const id = Number(key[1]);
// If the the value is an array
// return a new array of mapped data
// Otherwise return an array containing
// one object
const answers = Array.isArray(value)
? value.map(el => ({ answer: el }))
: [{ answer: value }];
// Return the new object
return { id, answers };
});
console.log(out);
lets create a pure function which accepts the object in the array like so
const processObject = obj => Object.keys(obj).map(id => {
const answer = obj[id];
const answers = Array.isArray(answer) ? answer : [answer]
const answerObjectArray = answers.map(ans => ({
answer: ans
}));
return {
id: +id.substring(1),
answers: answerObjectArray
}
});
const dataArray = [{
"q1": "5",
"q2": [
"13",
"12",
],
"q3": "test",
}];
const output = processObject(dataArray[0]);
console.log(output);

Renaming object properties in an array of objects

I have the following structure:
const data = {
invoices: [
{
Date: "2018-12-18T00:00:00.000Z",
InvoiceNumber: "59"
},
{
Date: "2018-12-18T00:00:00.000Z",
InvoiceNumber: "59"
}
]
};
I am wanting to re-name all instances of InvoiceNumber to CreditNoteNumber to give me the following:
const data = {
invoices: [
{
Date: "2018-12-18T00:00:00.000Z",
CreditNoteNumber: "59"
},
{
Date: "2018-12-18T00:00:00.000Z",
CreditNoteNumber: "59"
}
]
};
I have tried various things like the following for example:
var changed = data.invoices.map(function(item) {
return {
...data.invoices,
CreditNoteNumber: item.InvoiceNumber
};
});
However the spread pushes CreditNoteNumber outside the object.
Just use destructure and rename
const data = {
invoices: [
{
Date: "2018-12-18T00:00:00.000Z",
InvoiceNumber: "59"
},
{
Date: "2018-12-18T00:00:00.000Z",
InvoiceNumber: "59"
}
]
};
var changed = data.invoices.map(
({ Date, InvoiceNumber: CreditNoteNumber }) => ({ Date, CreditNoteNumber })
);
console.log(changed);
There is no such operation as "renaming" a property in JavaScript.
You will need to delete the property you no longer wish to keep:
const data = {
invoices: [
{
Date: "2018-12-18T00:00:00.000Z",
InvoiceNumber: "59"
},
{
Date: "2018-12-18T00:00:00.000Z",
InvoiceNumber: "59"
}
]
};
const changed = data.invoices.map(item => {
const obj = {
...item,
CreditNoteNumber: item.InvoiceNumber
};
delete obj.InvoiceNumber
return obj
});
console.log(changed)
var changed = data.invoices.map(function(item) {
return {
Date: item.Date,
CreditNoteNumber: item.InvoiceNumber
};
});
You can use the function map along with the function Object.assign as follow:
The following approach doesn't mutate the original object
const data = {invoices: [{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"},{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"}]},
result = data.invoices.map(({InvoiceNumber: CreditNoteNumber, ...items}) => Object.assign({}, items, {CreditNoteNumber}));
console.log(result);
If you want to mutate the original object, you can use a forEach instead:
const data = {invoices: [{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"},{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"}]};
data.invoices.forEach((item) => {
item.CreditNoteNumber = item.InvoiceNumber;
delete item.InvoiceNumber;
});
console.log(data);
the best option is to create a new object with the property item.CreditNoteNumber
and use a for each loop to iterate and reassign the values to the new object.
once the new object is created, assign the new object to the original object
data.invoices.
const data = {invoices: [{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"},{Date: "2018-12-18T00:00:00.000Z",InvoiceNumber: "59"}]};
var newInvoices = [];
data.invoices.forEach((item) => {
let invoice = {};
invoice.Date = item.Date;
invoice.CreditNoteNumber = item.InvoiceNumber;
newInvoice.push(invoice);
});
data.invoices = newInvoices;
console.log(data.invoices);

How do I get the latest timestamp for each month in an array

I have an array with a bunch of objects and some key/value pairs + timestamp (moment.js formatted timestamp) in it.
I have many timestamps for 12 months in total and need to get the last timestamp for each month and drop the other objects.
Actually I don't even know how to start off.
I used _.sortBy to order the array by date already but don't know how to move on.
array1 = [
{name:name1,timestamp:2018-09-15T07:00:00.0},
{name:name2,timestamp:2018-09-15T12:00:00.0},
{name:name3,timestamp:2018-09-28T05:00:00.0},
{name:name4,timestamp:2018-09-30T01:00:00.0},
{name:name5,timestamp:2018-10-02T10:00:00.0},
{name:name6,timestamp:2018-10-02T11:00:00.0},
{name:name7,timestamp:2018-10-15T07:00:00.0},
{name:name8,timestamp:2018-12-05T08:00:00.0},
{name:name9,timestamp:2018-12-05T09:00:00.0},
{name:name10,timestamp:2018-12-05T10:00:00.0}
]
expected result is
array1 = [
{name:name4,timestamp:2018-09-30T01:00:00.0},
{name:name7,timestamp:2018-10-15T07:00:00.0},
{name:name10,timestamp:2018-12-05T10:00:00.0}
]
reduce the array to an object having months as keys, overwriting they keys evrytime you find them, then your result is the array of Object.values` :
const array1 = [
{ name: "name1", timestamp: "2018-09-15T07:00:00.0" },
{ name: "name2", timestamp: "2018-09-15T12:00:00.0" },
{ name: "name3", timestamp: "2018-09-28T05:00:00.0" },
{ name: "name4", timestamp: "2018-09-30T01:00:00.0" },
{ name: "name5", timestamp: "2018-10-02T10:00:00.0" },
{ name: "name6", timestamp: "2018-10-02T11:00:00.0" },
{ name: "name7", timestamp: "2018-10-15T07:00:00.0" },
{ name: "name8", timestamp: "2018-12-05T08:00:00.0" },
{ name: "name9", timestamp: "2018-12-05T09:00:00.0" },
{ name: "name10", timestamp: "2018-12-05T10:00:00.0" }
];
const result = array1.reduce((acc, curr) => {
const month = new Date(curr.timestamp).getMonth() + 1;
acc[month] = curr;
return acc;
}, {});
console.log(Object.values(result));
You could take the date part, and store each entry in a hastable under that date. Thus, every entry with the same month will override the previous one, and the last one will be kept:
const byMonth = {};
for(const { name, timestamp } of array1) {
const month = timestamp.slice(0, 7);
byMonth[month] = { name, timestamp };
}
const result = Object.values(byMonth);
const array1 = [
{name:"name1",timestamp:"2018-09-15T07:00:00.0"},
{name:"name2",timestamp:"2018-09-15T12:00:00.0"},
{name:"name3",timestamp:"2018-09-28T05:00:00.0"},
{name:"name4",timestamp:"2018-09-30T01:00:00.0"},
{name:"name5",timestamp:"2018-10-02T10:00:00.0"},
{name:"name6",timestamp:"2018-10-02T11:00:00.0"},
{name:"name7",timestamp:"2018-10-15T07:00:00.0"},
{name:"name8",timestamp:"2018-12-05T08:00:00.0"},
{name:"name9",timestamp:"2018-12-05T09:00:00.0"},
{name:"name10",timestamp:"2018-12-05T10:00:00.0"}
];
const byMonth = {};
for(const { name, timestamp } of array1) {
const month = timestamp.slice(0, 7);
byMonth[month] = { name, timestamp };
}
const result = Object.values(byMonth);
console.log(result);

group dates by week javascript

I have the array of Persian dates and I want to group dates by the week.
for example, I have the following array:
[
"1396-10-11 09:07:21",
"1396-10-10 10:03:51",
"1396-10-07 02:07:02",
"1396-11-27 08:02:45",
"1396-11-19 01:02:32",
"1396-12-01 22:13:21",
"1396-02-12 09:07:21",
"1396-05-18 04:02:29",
"1396-05-21 14:01:42",
"1396-07-11 01:16:29"
]
and I want to groupBy dates by the week.
I wrote following code but not working good:
Array.prototype.groupBy = function(prop) {
return this.reduce(function(groups, item) {
var val = item[prop];
groups[val] = groups[val] || [];
groups[val].push(item);
return groups;
}, {});
}
const formatted = dates.map(elem => {
return {
numberOfWeek: moment(elem.date, 'jYYYY-jMM-jDD').startOf('jMonth').jWeek(),
date: moment(elem.date, 'jYYYY-jMM-jDD').format('jYYYY-jMM-jDD'),
score: elem.score
};
});
You can use moment().week() to get the week number of the year and then group by it, here is a working example, I used array.reduce to create a new object of dates grouped by the week number:
const dates = [
"1396-10-11 09:07:21",
"1396-10-10 10:03:51",
"1396-10-07 02:07:02",
"1396-11-27 08:02:45",
"1396-11-19 01:02:32",
"1396-12-01 22:13:21",
"1396-02-12 09:07:21",
"1396-05-18 04:02:29",
"1396-05-21 14:01:42",
"1396-07-11 01:16:29"
];
const groups = dates.reduce((acc, date) => {
// create a composed key: 'year-week'
const yearWeek = `${moment(date).year()}-${moment(date).week()}`;
// add this key as a property to the result object
if (!acc[yearWeek]) {
acc[yearWeek] = [];
}
// push the current date that belongs to the year-week calculated befor
acc[yearWeek].push(date);
return acc;
}, {});
console.log(groups);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
Another simple way of achieving the same with Lodash would be as follows:
const groupBy = require('lodash/groupBy');
const moment = require('moment');
const data = [
"1396-10-11 09:07:21",
"1396-10-10 10:03:51",
"1396-10-07 02:07:02",
"1396-11-27 08:02:45",
"1396-11-19 01:02:32",
"1396-12-01 22:13:21",
"1396-02-12 09:07:21",
"1396-05-18 04:02:29",
"1396-05-21 14:01:42",
"1396-07-11 01:16:29"
];
groupBy(data, (dt) => moment(dt).week());
Result is as follows:
{
'7': [ '1396-02-12 09:07:21' ],
'21': [ '1396-05-18 04:02:29', '1396-05-21 14:01:42' ],
'29': [ '1396-07-11 01:16:29' ],
'41': [ '1396-10-07 02:07:02' ],
'42': [ '1396-10-11 09:07:21', '1396-10-10 10:03:51' ],
'47': [ '1396-11-19 01:02:32' ],
'49': [ '1396-11-27 08:02:45', '1396-12-01 22:13:21' ]
}

Categories

Resources