Reputation: 902
I have a JSON like this:
{
"prerequisites": [
"مدل سازی",
"دینامیک",
"استاتیک"
],
"targets": [
"دانشجویان هوافضا",
"دانشجویان مکانیک",
"دانشجویان عمران",
"دانشجویان مهندسی دریا"
],
"sections": [
{
"title": "چگونه آباکوس را نصب کنیم.",
"achievements": [
"چگونه کامپیوتر را روشن کنیم",
"چگونه آباکوس را نصب کنیم",
"چگونه آباکوس را باز کنیم."
],
"lectures": [
{
"title": "آموزش روشن کردن ویندوز",
"media": "آدرس فایل pdf یا ویدیو"
},
{
"title": "آموزش روشن کردن ویندوز",
"media": "آدرس فایل pdf یا ویدیو"
}
]
}
]
}
As you see I have a sections property and in each section, I have a lecture s array,
I want to push paired key, value {"unlock_users": 0}
to all element of lectures array in TypeScript, How can I do this in TypeScript (angular 5).
I have tested the following code to find the index and and push by index but it returns undefined for index:
for (const {section, index_s} of this.data['sections'].map((item, index) => ({ item, index }))) {
console.log(section);
console.log(index_s);
for (const {lecture, index_l} of section['lectures']map((item, index) => ({ item, index }))) {
console.log(lecture);
this.data['sections'][index_s]['lectures'][index_l]['unlock_users'] = 0;
}
}
Upvotes: 0
Views: 78
Reputation: 2376
You can do this by using Array.prototype.map
like below:
let json = `{
"prerequisites": [
"مدل سازی",
"دینامیک",
"استاتیک"
],
"targets": [
"دانشجویان هوافضا",
"دانشجویان مکانیک",
"دانشجویان عمران",
"دانشجویان مهندسی دریا"
],
"sections": [
{
"title": "چگونه آباکوس را نصب کنیم.",
"achievements": [
"چگونه کامپیوتر را روشن کنیم",
"چگونه آباکوس را نصب کنیم",
"چگونه آباکوس را باز کنیم."
],
"lectures": [
{
"title": "آموزش روشن کردن ویندوز",
"media": "آدرس فایل pdf یا ویدیو"
},
{
"title": "آموزش روشن کردن ویندوز",
"media": "آدرس فایل pdf یا ویدیو"
}
]
}
]
}`;
let o = JSON.parse(json);
o.sections = o.sections.map(obj => {
obj.lectures = obj.lectures.map(lec => {
lec.unlock_users = 0;
return lec;
});
return obj
});
console.log(o.sections);
Upvotes: 1