javascript error SyntaxError: missing : after property id - javascript

Trying to make an array of strings inside array of objects and getting an error saying SyntaxError: missing : after property id for the code below in javascript
let movies = [
{
movie title: 'Avengers: Age of Ultron',
release year: '2015',
rating:'7.3',
"genres"=[0:"Action",1:"Adventure",2:"Sci-Fi"]
},
{
movie title: 'The Dark Knight',
release year:'2008',
rating:'9.0',
genres:["Action","Crime","Drama"]
},
{
movie title: 'Forrest Gump',
release year:'1994',
rating:'8.8',
genres:["Drama","Romance"]
},
{
movie title: 'Inception',
release year:'2010',
rating:'8.8',
genres:["Action","Adventure","Sci-Fi"]
},
{
movie title: 'The Matrix',
release year:'1999',
rating:'8.7',
genres:["Action","Sci-Fi"]
},
{
movie title: 'Border',
release year:'1997',
rating:'7.9',
genres:["Action","Drama","History"]
}
];

There are two mistakes in your code.
If JSON object key contains ' ', you should write ".
You don't need to write an index to your JSON object value.
Here's the updated code.
let movies = [
{
"movie title": 'Avengers: Age of Ultron',
"release year": '2015',
rating:'7.3',
genres:["Action", "Adventure", "Sci-Fi"]
},
{
"movie title": 'The Dark Knight',
"release year":'2008',
rating:'9.0',
genres:["Action","Crime","Drama"]
},
{
"movie title": 'Forrest Gump',
"release year":'1994',
rating:'8.8',
genres:["Drama","Romance"]
},
{
"movie title": 'Inception',
"release year":'2010',
rating:'8.8',
genres:["Action","Adventure","Sci-Fi"]
},
{
"movie title": 'The Matrix',
"release year":'1999',
rating:'8.7',
genres:["Action","Sci-Fi"]
},
{
"movie title": 'Border',
"release year":'1997',
rating:'7.9',
genres:["Action","Drama","History"]
}
];

Related

Why ng2-tree is showing undefined

I'm using ng2-tree https://angular2-tree.readme.io/v3.2.0/docs/inputs plugin
When i input below json it is showing as undefined
[
{
"value": "helper",
"name": "helper",
"children": []
},
{
"value": "taxi",
"name": "taxi",
"children": []
},
{
"value": "Cake",
"name": "Cake",
"children": [
{
"name": "Chocolate Fudge Cake",
"value": "Chocolate Fudge Cake"
},
{
"name": "Carrot & Walnut Cake",
"value": "Carrot & Walnut Cake"
}
]
}
]
with above json my result is as undefined you can see them in my provided link below
here is the stackblitz link: https://stackblitz.com/edit/angular-ng2-tree-aouyza?file=app/app.component.ts
Please help me thanks in advance!!
Your data structure is wrong. The tree component received as input param a TreeModel and you're having an array of TreeModels at the moment.
Either you adjust your data structure and use a parent TreeModel to wrap your current ones as its children, like following:
tree: TreeModel = {
value: 'Parent Model',
children: [
{
value: 'helper',
name: 'helper',
children: [],
},
{
value: 'taxi',
name: 'taxi',
children: [],
},
{
value: 'Cake',
name: 'Cake',
children: [
{
name: 'Chocolate Fudge Cake',
value: 'Chocolate Fudge Cake',
},
{
name: 'Carrot & Walnut Cake',
value: 'Carrot & Walnut Cake',
},
],
}
]
};
Or you iterate over the array in the HTML and use multiple tree components. That would look like following:
<tree [tree]="t" *ngFor="let t of tree"></tree>
For more information see the Github page of ng2-tree ;)
Update:
You still need to adjust the data model the way I suggested but you can hide the empty root node. To do so, you need to do following:
HTML
<tree [tree]="tree" [settings]="{ rootIsVisible: false }"></tree>
Due to this setting a class rootless is applied which hides the empyt root node but only if you've added node_modules/ng2-tree/styles.css to your angular.json or you've added a custom implementation for that class.
You can find the settings doc here.

Sort an array of objects(with multiple properties) in a specified order of Keys with JavaScript [duplicate]

This question already has answers here:
Sort JavaScript object by key
(37 answers)
Closed 2 years ago.
I have a json response with the following data in alphabetical order,
let sheetCells =
{
0: [
{
"Actual Hours": 16
"Assigned": "Jerry"
"Completion %": 48.2
"Days Scheduled": 2
"Device 1": 10
"Device 2": 43
"Device 3": 72
"Device 4": 91
"Device 5": 25
"End Date": "2018-01-03T23:00:00.000Z"
"Estimated Hours": 16
"ID": "1dbk3"
"Notes": "Note 1"
"Parent ID": "2k59f"
"Priority": ""
"Start Date": "2018-01-01T23:00:00.000Z"
"Stories": "A User"
"Tests": "Y"
},
{
//...same keys as above, different values
}
]
}
but this is the DESIRED format in which I want the resulting objects in the array be sorted,
[
{
"Stories": "A User"
"ID": "1dbk3"
"Parent ID": "2k59f"
"Completion %": 48.2
"Priority": ""
"Device 1": 10
"Device 2": 43
"Device 3": 72
"Device 4": 91
"Device 5": 25
"Assigned": "Jerry"
"Notes": "Note 1"
"Tests": "Y"
"Estimated Hours": 16
"Days Scheduled": 2
"Start Date": "2018-01-01T23:00:00.000Z"
"End Date": "2018-01-03T23:00:00.000Z"
"Actual Hours": 16
},
{
//...same keys as above, different values
}
]
Here is the solution that i've tried
let sortOrder = ['Stories', 'ID', 'Parent ID', 'Completion %', 'Priority', 'Device 1', 'Device 2', 'Device 3', 'Device 4', 'Device 5', 'Assigned', 'Notes', 'Tests', 'Estimated Hours', 'Days Scheduled', 'Start Date', 'End Date', 'Actual Hours']
let result = sheetCells[0].sort((a,b) => sortOrder.indexOf(a.Stories) > sortOrder.indexOf(b.Stories)))
but this result gets just the story key and ignores the rest, please help with a working and optimal solution.Thanks
Rather than resorting the original data, you can map it to a new sorted array by indexing it with every element in your sortOrder in order. Something like this:
let result = sortOrder.map(key => sheetCells[0][key]);
While that's a working version of your solution, based on the data structure in your example, this may be closer to what you're looking for:
let result = sheetCells[0].map(cell => sortOrder.map(key => cell[key]));

Angular Changing/Replacing the value in a string based on the User selection

I am working on an offer letter template that will replace/modify Dynamic Data Points like Name, Address, Role, Salary, etc based on the candidate selected from a list of candidates. There is a fixed syntax for a dynamic data points i.e they will be enclosed within <<>>, for example :
Welcome to the family, <<Name>>
You will be paid <<Salary>> for the duration of your employment.
In other words, these few data points will change by selecting the candidate we want to offer the job and the rest of the template will remain the same. Here is a demo to help you understand.
This is a dummy array I have created with 1 template, In the real-world app, I can have many templates with different clauseNames, so I am looking for a permanent fix.
.ts file, Template List :
[{
templateId: 1,
templateName: "Offer",
clauses: [
{
clauseName: "Introduction",
clauseId: 1,
texts: [
{
text: "Hello <<Name>>, Welcome to the Machine",
textId: 1,
}]
},
{
clauseName: "Address",
clauseId: 2,
texts: [
{
text: "<<Address>>",
textId: 2,
}]
},
{
clauseName: "Date Of Joining",
clauseId: 3,
texts: [
{
text: "You can join us on <<DateOfJoining>>",
textId: 3,
}]
},
]
}]
and here is the candidate list,
candidateList = [
{ name: "Simba", address: "Some Random Cave" },
{ name: "Doe John", address: "line 4, binary avenue, Mobo" },
{ name: "B Rabbit", address: "8 mile road, Detroit" },
{ name: "Peter Griffin", address: "Spooner Street" },
{ name: "Speedy Gonzales", address: "401, hole 34, Slyvester Cat Road" },
{ name: "Morty", address: "Time Machine XYZ" },
{ name: "Brock", address: "pokeball 420, Medic center" },
]
You can use regular expressions to replace those placeholders such as:
var result = text.text.replace(/\<\<(.*?)\>\>/g, function(match, token) {
return candidate[token.toLowerCase()];
});
One way to incorporate this to your display is by creating a property that returns the formatted text.
I have updated your stackblitz here.
Take a look at this demo
I have modified the logic in below method:
showTeplate(name,address,doj) {
this.clauseList = [];
for (let a of this.templateList) {
if (a.clauses != null) {
for (let cl of a.clauses) {
const tempObj = JSON.parse(JSON.stringify(cl));
tempObj.texts.forEach(textObj => {
textObj.text = textObj.text.replace("<<Name>>",name);
textObj.text = textObj.text.replace("<<Address>>",address);
textObj.text = textObj.text.replace("<<DateOfJoining>>",doj);
})
this.clauseList.push(tempObj)
}
}
}
console.log("Clause list", this.clauseList)
}

Destructuring an array of objects (es6)

I'm wondering how to destructure an array of objects. I'm attempting to destructure country from the partner array. It is a project requirement that partner be an array of objects, even though there should only ever be one partner country per obj.
arr = [
{ title: "Title A",
desc: "Desc A",
role: {role_desc: "Role Desc A", role_name: "Role A"},
partner: [{country: "Brazil", region: "SA"}]
},
{ title: "Title B",
desc: "Desc B",
role: {role_desc: "Role Desc B", role_name: "Role B"},
partner: [{country: "US", region: "NA"}]
}
]
I am able to populate a table with data for all fields except partner.
arr.map(
({ title, desc, role: {role_name}, partner: [{country}] }) =>
({ title, desc, role: {role_name}, partner: [{country}] })
);
I've referred to Destructure object properties inside array for all elements and Destructuring an array of objects with es6, and it looks like it is not possible to do this without transforming the data first.
Any help would be appreciated (and apologies for the dupe).
You can simply use default value when you want to handle the case when partner is empty array,
const arr = [{ title: "Title A",desc: "Desc A",role: {role_desc: "Role Desc A", role_name: "Role A"},partner: [{country: "Brazil", region: "SA"}]},{ title: "Title B",desc: "Desc B",role: {role_desc: "Role Desc B", role_name: "Role B"},partner: [{country: "US", region: "NA"}]},{ title: "Title C",desc: "Desc C",role: {role_desc: "Role Desc C", role_name: "Role C"},partner: []}]
const final = arr.map(
({ title, desc, role: {role_name}, partner}) =>
({ title, desc, role: {role_name}, partner:[ {country} = {country: undefined } ] })
);
console.log(final)
That being said we should keep our code as readable as possible, here it becomes so hard on eyes instead of trying to save one extra line, we should opt for making it more readable
const arr = [{ title: "Title A",desc: "Desc A",role: {role_desc: "Role Desc A", role_name: "Role A"},partner: [{country: "Brazil", region: "SA"}]},{ title: "Title B",desc: "Desc B",role: {role_desc: "Role Desc B", role_name: "Role B"},partner: [{country: "US", region: "NA"}]},{ title: "Title C",desc: "Desc C",role: {role_desc: "Role Desc C", role_name: "Role C"},partner: []}]
const final = arr.map(
({ title, desc, role: {role_name}, partner}) => {
let country = partner[0] && partner[0].country || undefined
return { title, desc, role: {role_name}, partner:[ {country}] }
}
);
console.log(final)
I was overlooking a very simple answer due to an equally simple error:
arr.map(
({ title, desc, role: {role_name}, partner}) =>
({ title, desc, role: {role_name}, partner: (partner[0] && partner[0].country) || 'Undefined' })
);
Every item in the array did not necessarily have a "country" property. For certain items, partner is just an empty array. The above fixed the issue.
I agree that it doesn't make sense to make partner an array if it will only ever contain one object. Client requirements, however.

could not read json data using jquery with for loop

I have a data object and inside that I have data object with json data inside. Here is how is looks like. the name of the file is data.js
var data =
[
{
title: 'this is title one',
commit: 'this is commit'
},
{
title: 'this is title two',
commit: 'this is commit'
},
{
title: 'this is title three',
commit: 'this is commit'
},
{
title: 'this is title four',
commit: 'this is commit'
},
{
title: 'this is title five',
commit: 'this is commit'
},
{
title: 'this is title six',
commit: 'this is commit'
},
{
title: 'this is title seven',
commit: 'this is commit'
}
]
here is my code
for (var i = 0; i < data.length; i++) {
$(container).load(view, function () {
console.log(data[i].title);
li.append('<img src="../images/profile.png" alt="Profile photo" />');
li.append('<span class="commit">' + data[i].title + '</span>');
li.append('<p>' + data.commit + '</p>');
li.append('<section class="clear"></section>');
$('#home ul').append(li);
});
}
Now I am getting this error in my console
Cannot read property 'title' of undefined
above error is on this line
li.append('<span class="commit">' + data[i].title + '</span>');
how to fix this?
Well, data.js is not really json.
First switch from load() to getJSON()
$.getJSON(view, function(data) { })
next remove the line
var data =
just have the json contents. jQuery will assign JSON to argument data.
Your json array contains errors.
You can validate your json here http://json.parser.online.fr/
Must be so:
{
"title": ["this is title one", "this is title two", "this is title three", "this is title four", "this is title five", "this is title six", "this is title seven" ]
,
"commit": [ "this is commit", "this is commit", "this is commit", "this is commit", "this is commit", "this is commit", "this is commit" ]
}

Categories

Resources