how to change JSON Nested array property "project_id" with "project_name" - javascript

Trouble:
[
{
"project_id": 1,
"project_name": "CDP",
"role": "PL"
},
{
"project_id": 2,
"project_name": "Admincer",
"role": "PM"
},
I want to add the "project_id" property from the above three properties to another array using some method.
My idea is: 1. First of all, if I could copy the "project_id" property of this array to the second Nested JSON array, it would be fine.
What I looked up:
const obj = {
"project_id": 1,
"project_name": "CDP",
"role": "PL"
};;
const objCopy = {
"start_time": "09:00:00",
"end_time": "18:00:00",
"rest_time": "01:00:00",
"worked_time": "08:00:00",
"is_wfh": true,
"id": 1, 1,
"work_day_id": 45,
"time_cards": [
{
... obj
}
]
};;
console.log (objCopy);
I found that I could copy it this way.
I tried the above code in Chrome Console.
The array was copied, but the entire object was copied. I just want to copy the properties of project_id.
I want to create a new property called "prj_name" in this array and display only that property in Vuetify.
async fetchWorkerTimeCard() {
try {
this.worker_data = []
await this.$axios.$get('/worker_time_card', {
params: {
work_date: this.calendarVal
}
}).then(data => {
this.worker_data = data
})
var projects = await this.fetch_worker_projects()
console.log(projects)
} catch (error) {
console.log(error)
this.worker_data = []
}
},
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.5/vue.js"></script>
<v-card>
<v-data-table v-if="worker_data.time_cards" :headers="headers2" :items="worker_data.time_cards"></v-data-table>
</v-card>

You can simply change your object data like any other object in JS.
const obj = {
"project_id": 1,
"project_name": "CDP",
"role": "PL"
};
const objCopy = {
"start_time": "09:00:00",
"end_time": "18:00:00",
"rest_time": "01:00:00",
"worked_time": "08:00:00",
"is_wfh": true,
"id": 1,
"work_day_id": 45
}
console.log({...obj, ...objCopy})
This will create 1 object that merged.
Or if you just want to project_id value then just change it like:
objCopy.project_id = obj.project_id

If I'm understanding your first question correctly, you might be interested in the map function, which allows you to create a new array from an existing array. So, for example, if the first snippet you posted is an array of objects we call projects, you could use:
var projectIds = projects.map(p => p.project_id), where projectIds would now be an array of just project ids.
It seems like you might be asking more than this though, so I second Bravo's request for more clarification/reorganization in your question.

I'm not pretty sure if you want either of the following results:
{
"start_time": "09:00:00",
"end_time": "18:00:00",
"rest_time": "01:00:00",
"worked_time": "08:00:00",
"is_wfh": true,
"id": [
1,
1
],
"work_day_id": 45,
"time_cards": [
{
"project_id": 1
},
{
"project_id": 2
}
]
}
or this
{
"start_time": "09:00:00",
"end_time": "18:00:00",
"rest_time": "01:00:00",
"worked_time": "08:00:00",
"is_wfh": true,
"id": [
1,
1
],
"work_day_id": 45,
"time_cards": [
"project_id": [1, 2]
}
In case you need the first scenario, the following code may help you:
// This function return an array with: [{project_id: Number}]
function onlyIds(obj) {
const ids = [];
// Iterate the obj Array
obj.forEach(element => {
// Push a new JSON: "{project_id: 1}" or whatever
ids.push({ project_id: element.project_id });
});
// return an array that only contains the project_id
return ids;
}
const obj = [
{
project_id: 1,
project_name: 'CDP',
role: 'PL',
},
{
project_id: 2,
project_name: 'Admincer',
role: 'PM',
},
];
const objCopy = {
start_time: '09:00:00',
end_time: '18:00:00',
rest_time: '01:00:00',
worked_time: '08:00:00',
is_wfh: true,
id: [1, 1],
work_day_id: 45,
time_cards: onlyIds(obj),
};
console.log(onlyIds(obj));
console.log(objCopy);
I'm pretty sure there should be any more elegant/optimal way (as using any kind of higher-order function I may be missing right now) but as far as I understood, this should do the job.

Related

How to get this output from JSON in javascipt ny comparing student_id from mark_details and students_detail?

JSON Object:
{
"students_detail": [
{
"student_id": 1,
"name": "abc",
"roll_number": 10
},
{
"student_id": 2,
"name": "pqr",
"roll_number": 12
}
],
"subject_details": [
{
"subject_id": 1,
"subject_name": "math"
},
{
"subject_id": 2,
"subject_name": "english"
}
],
"exam_details": [
{
"exam_id": 1,
"exam_name": "Prelim"
}
],
"mark_details": [
{
"id": 1,
"exam_id": 1,
"subject_id": 1,
"student_id": 1,
"mark": 51
},
{
"id": 2,
"exam_id": 1,
"subject_id": 2,
"student_id": 2,
"mark": 61
}
]
}
Ouptut:
{
"student_mark_details": [
{
"abc": {
"roll_number": 10,
"Prelim": [
{
"subject_name": "math",
"mark": 51
}
]
},
"pqr": {
"roll_number": 12,
"Prelim": [
{
"subject_name": "english",
"mark": 61
}
]
}
}
]
}
i tried using loops and accesing student_id in both object and comparing them but code gets too messy and complex,is there any way i can use map() or filter() in this or any other method.
i have no idea where to start,my brain is fried i know im asking lot but help will be appreciated (any link/source where i can learn this is fine too)
Your output object really has a weird format: student_mark_details is an array of size 1 that contains an object that has all your students in it. Anyway, this should give you what you need. It is a format that you find often because it is a system with primary key and secondary key used a lot in databases.
The key to manage that is to start with what is at the core of what you are looking for (here, you want to describe students, so you should start from there), and then navigate the informations you need by using the primary/secondary keys. In JS, you can use the find() function in the case where one secondary key can be linked only to one primary key (ex: one mark is linked to one exam), and the filter() function when a secondary key can be linked to multiple secondary keys (ex: a student is linked to many grades).
I am not sure if this is 100% what you need because there are maybe some rules that are not shown in your example, but it solves the problem you submitted here. You might have to test it and change it depending of those rules. I don't know what your level is so I commented a lot
const data = {
"students_detail": [
{
"student_id": 1,
"name": "abc",
"roll_number": 10
},
{
"student_id": 2,
"name": "pqr",
"roll_number": 12
}
],
"subject_details": [
{
"subject_id": 1,
"subject_name": "math"
},
{
"subject_id": 2,
"subject_name": "english"
}
],
"exam_details": [
{
"exam_id": 1,
"exam_name": "Prelim"
}
],
"mark_details": [
{
"id": 1,
"exam_id": 1,
"subject_id": 1,
"student_id": 1,
"mark": 51
},
{
"id": 2,
"exam_id": 1,
"subject_id": 2,
"student_id": 2,
"mark": 61
}
]
}
function format(data) {
const output = {
"student_mark_details": [{}]
};
//I start by looping over the students_detail because in the output we want a sumary by student
data.students_detail.forEach(student => {
//Initialization of an object for a particular student
const individualStudentOutput = {}
const studentId = student.student_id;
const studentName = student.name;
//The rollNumber is easy to get
individualStudentOutput.roll_number = student.roll_number;
//We then want to find the exams that are linked to our student. We do not have that link directly, but we know that our student is linked to some marks
//Finds all the marks that correspond to the student
const studentMarkDetails = data.mark_details.filter(mark => mark.id === studentId);
studentMarkDetails.forEach(individualMark => {
//Finds the exam that corresponds to our mark
const examDetail = data.exam_details.find(exam => individualMark.exam_id === exam.exam_id);
//Finds the subject that corresponds to our mark
const subjectDetail = data.subject_details.find(subject => individualMark.subject_id === subject.subject_id);
//We then create a grade that we will add to our exam
const grade = {
subject_name: subjectDetail.subject_name,
mark: individualMark.mark
}
//We then want to add our grade to our exam, but we don't know if our output has already have an array to represent our exam
//So in the case where it does not exist, we create one
if (!individualStudentOutput[examDetail.exam_name]) {
individualStudentOutput[examDetail.exam_name] = [];
}
//We then add our grade to the exam
individualStudentOutput[examDetail.exam_name].push(grade);
});
//Now that we have finished our individual output for a student, we add it to our object
output.student_mark_details[0][studentName] = individualStudentOutput;
})
return output;
}
console.log(JSON.stringify(format(data)))

Sort max date from Object

Trying to sort the object with the max date. One id may have multiples dates. Below is the format of the object where id:123 has two dates. So I am trying to take the max date for the user 123. I used the sort method and storing the array[0] but still there is something missing.
var arr = [
{
"scores": [
{
"score": 10,
"date": "2021-06-05T00:00:00"
}
],
"id": "3212"
},
{
"scores": [
{
"score": 10,
"date": "2021-06-05T00:00:00"
},
{
"score": 20,
"date": "2021-05-05T00:00:00"
}
],
"id": "123"
},
{
"scores": [
{
"score": 5,
"date": "2021-05-05T00:00:00"
}
],
"id": "321"
}
]
What I tried is
_.each(arr, function (users) {
users.scores = users.scores.filter(scores => new Date(Math.max.apply(null, scores.date)));
return users;
});
Expecting the output to look like the following with the max date selected.
[
{
"scores": [
{
"score": 10,
"date": "2021-06-05T00:00:00"
}
],
"id": "3212"
},
{
"scores": [
{
"score": 10,
"date": "2021-06-05T00:00:00"
}
],
"id": "123"
},
{
"scores": [
{
"score": 5,
"date": "2021-05-05T00:00:00"
}
],
"id": "321"
}
]
Your filter callback function is not performing a comparison to filter the correct element. Also, although applying the "maximum" algorithm on the dates as string would be fine in your case (because of the date format you have), it would be much safer to transform the date strings into date objects to consistantly get correct results regardless of the format.
In the solution below, you can use a combination of Array.map() and Array.sort() to copy and process your data in the correct result.
const data = [{
'scores': [{
'score': 10,
'date': '2021-06-05T00:00:00'
}],
'id': '3212'
}, {
'scores': [{
'score': 10,
'date': '2021-06-05T00:00:00'
}, {
'score': 20,
'date': '2021-05-05T00:00:00'
}],
'id': '123'
}, {
'scores': [{
'score': 5,
'date': '2021-05-05T00:00:00'
}],
'id': '321'
}];
// map the data and return the updated objects as the result
const result = data.map((user) => {
// copy the scores array to not mutate the original data
const sortedScores = user.scores.slice();
// sort the scores array by date descending
sortedScores.sort((a, b) => (new Date(b.date) - new Date(a.date)));
// return the same user with the first score from the sorted array
return {
...user,
scores: [sortedScores[0]]
};
});
console.log(result);

How can I add an element in object at certain position?

I have this object:
var ages = [{
"getasafieldDetail": {
"id": "xxx",
"asaentrySet": [{
"result": "ON",
"buy": {
"username": "Dis"
},
"offerSet": [{
"createdStr": "2001-08-09 at 11:52 pm",
"value": 5.0
}]
}]
}
}];
and i want to add an element and have an output like this:
var ages = [{
"getasafieldDetail": {
"id": "xxx",
"asaentrySet": [{
"result": "ON",
"buy": {
"username": "Dis"
},
"land": "111", // THIS <<<<------------
"offerSet": [{
"createdStr": "2001-08-09 at 11:52 pm",
"value": 5.0
}]
}]
}
}];
i tried using splice but not works...
ages.splice(ages[0]['getasafieldDetail']['asaentrySet'][0]['offerSet'],0,'"land": "111"');
ages.join();
There is the handy syntax of Destructuring assignments which helps with cutting and reassembling objects.
Edit
#FireFuro99 did point to the ES6/ES2015 spec which explicitly states how to preserve/handle an object's key-order at the object's creation time.
Thus one can say ...
Every JS engine which does support Destructuring assignment has to respect too any object's key order from/at this object's creation time.
const ages = [{
getasafieldDetail: {
id: "xxx",
asaentrySet: [{
result: "ON",
buy: {
username: "Dis",
},
offerSet: [{
createdStr: "2001-08-09 at 11:52 pm",
value: 5.0,
}],
}],
},
}];
const { result, buy, ...rest } = ages[0].getasafieldDetail.asaentrySet[0];
ages[0].getasafieldDetail.asaentrySet[0] = {
result,
buy,
land: "111",
...rest,
};
console.log({ ages });
.as-console-wrapper { min-height: 100%!important; top: 0; }
Splice only works on Arrays.
To make this work, convert your Object to an Array using Object.entries(), then use splice, and then convert it back to an object using Object.fromEntries().
const entrySet = Object.entries(ages[0]['getasafieldDetail']['asaentrySet'][0]);
entrySet.splice(2,0, ["land", "111"]);
ages[0]['getasafieldDetail']['asaentrySet'][0] = Object.fromEntries(entrySet);
This will insert the key-value pair at the the specified position.
The advantage this has over the destructuring assignment is, that you can specify the index, whereas destructuring is pretty hardcoded.
ages[0]["getasafieldDetail"]["asaentrySet"][0].land = '111' will create the key land in the first object in asaentrySet and assign the value 111. Key order is not guaranteed
var ages = [{
"getasafieldDetail": {
"id": "xxx",
"asaentrySet": [{
"result": "ON",
"buy": {
"username": "Dis"
},
"offerSet": [{
"createdStr": "2001-08-09 at 11:52 pm",
"value": 5.0
}]
}]
}
}];
ages[0]["getasafieldDetail"]["asaentrySet"][0].land = '111'
console.log(ages)
When it is an array of objects you could simple, add, passing the position that you want by editing the array like the example below:
let land = {land: 1111}
let ages = [{'a':11},'2', 'wd']
let new =[]
new.push(ages[1])
new.push(land)
ages[1] = new
console.log(ages)
output:
(3) [{…}, Array(2), "wd"]
You get what you want from the array, edit it, and put back in the same position, may it can help.

Filtering and returning parent object using lodash chain

I want to use Lodash chain function to filter through an arrays nested array items and then return the full parent object.
Here is some dummy data from my use case to illustrate my issue:
const capital = [
{
"financeCategory": "Loans",
"financeCategoryId": "22HM6fFFwx9eK2P42Onc",
"financeElements": [
{
"financeCategoryId": "22HM6fFFwx9eK2P42Onc",
"financeElementId": "JQiqqvGEugVQuI0fN1xQ",
"financeElementTitle": "Convertible loan",
"data": [
{
"month": 1,
"value": 100,
"year": "2020"
},
{
"month": 1,
"value": 100,
"year": "2019"
},
],
}
]
},
{
"financeCategory": "Investments",
"financeCategoryId": "JtnUsk5M4oklIFk6cAlL",
"financeElements": []
},
{
"financeCategory": "Ownerships Contribution",
"financeCategoryId": "PaDhGBm5uF0PhKJ1l6WX",
"financeElements": []
}
];
I want to filter on the "data" array within the financeElements and then return full expense object with the filter applied on "data".
Let's say I want to manipulate the expense object and only get the data on the financeElements that have the year 2020. I've tried like so:
const expenseFiltered: any = _.chain(expenses)
.flatMap('financeElements')
.flatMap('data')
.filter({year: '2020' as any}).value();
But that just gives me the filtered "data" objects.
Output:
[{
"month": 1,
"value": 100,
"year": "2020"
}]
Now I know there are ways that I could use that to produce the full object with the filtered data, but I really want to do this in just one simple _.chain command
Desired output
[
{
"financeCategory": "Loans",
"financeCategoryId": "22HM6fFFwx9eK2P42Onc",
"financeElements": [
{
"financeCategoryId": "22HM6fFFwx9eK2P42Onc",
"financeElementId": "JQiqqvGEugVQuI0fN1xQ",
"financeElementTitle": "Convertible loan",
"data": [
{
"month": 1,
"value": 100,
"year": "2020"
}
],
}
]
},
{
"financeCategory": "Investments",
"financeCategoryId": "JtnUsk5M4oklIFk6cAlL",
"financeElements": []
},
{
"financeCategory": "Ownerships Contribution",
"financeCategoryId": "PaDhGBm5uF0PhKJ1l6WX",
"financeElements": []
}
]
Is this possible using lodash chain?
A chain is used to transform a structure in several steps. In your case, you don't want to change the structure. You can use nested Array.map() (or lodash's _.map()) calls to iterate and rebuild the structure, and internally _.filter() the data:
const capital = [{"financeCategory":"Loans","financeCategoryId":"22HM6fFFwx9eK2P42Onc","financeElements":[{"financeCategoryId":"22HM6fFFwx9eK2P42Onc","financeElementId":"JQiqqvGEugVQuI0fN1xQ","financeElementTitle":"Convertible loan","data":[{"month":1,"value":100,"year":"2020"},{"month":1,"value":100,"year":"2019"}]}]},{"financeCategory":"Investments","financeCategoryId":"JtnUsk5M4oklIFk6cAlL","financeElements":[]},{"financeCategory":"Ownerships Contribution","financeCategoryId":"PaDhGBm5uF0PhKJ1l6WX","financeElements":[]}];
const expenseFiltered = capital.map(ex => ({
...ex,
financeElements: ex.financeElements.map(fe => ({
...fe,
data: _.filter(fe.data, { year: '2020' })
}))
}));
console.log(expenseFiltered);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

How to get values of an array of dictionary from alamofire response using swift3

I'm trying to extract "translations" Array "text" and "verses" array "verse_key" data from below json response using Alamofire and swift3.
{
"verses": [
{
"id": 1,
"verse_number": 1,
"chapter_id": 1,
"verse_key": "1:1",
"text_madani": "بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ",
"text_indopak": "بِسْمِ اللّٰهِ الرَّحْمٰنِ الرَّحِيْمِ",
"text_simple": "بسم الله الرحمن الرحيم",
"juz_number": 1,
"hizb_number": 1,
"rub_number": 1,
"sajdah": null,
"sajdah_number": null,
"page_number": 1,
"audio": {
"url": "versesAbdulBaset/Mujawwad/mp3/001001.mp3",
"duration": 6,
],
"format": "mp3"
},
"translations": [
{
"id": 102574,
"language_name": "english",
"text": "In the name of Allah, the Beneficent, the Merciful.",
"resource_name": "Shakir",
"resource_id": 21
}
],
}
],
"meta": {
"current_page": 1,
"next_page": null,
"prev_page": null,
"total_pages": 1,
"total_count": 7
}
}
I'm new to swift and I can't find a way to achieve this. How can I get the values of "translations" Array "text" and "verses" array "verse_key" ?
thanks advance
Use swiftyJSON.
switch response.result{
case .success(let data) :
let json = JSON(data)
let verses = json["verses"].Stringvalue
print(verses) //get all verses
print(verses["verse_key"].Stringvalue) // get "verse_key"
break
You can take each values from this json by giving the key names. If you want to get the "verses" , use json["verses"].You can also use JSONdecoder.

Categories