Check if an object contains a property called format in Javascript - javascript

I have an array of movie objects in a web application, and each object has properties for title(string),release year(int),rating(int) and genre(an array of string e.g ['Action','Sci-Fi],now some of the movie objects got a property for format(string) while others don't.All I need is help iterating through these objects and checking which objects don't have a format property and add the property to these objects and set the values with Film for those that do not...
Here is the js code i tried so far
var fractured={
title:"Fractured",
release:2019,
rating:8,
format:"digital",
genre:[
"Mystery","Sci-Fi","Western"]
};
var countdown={
title:"Countdown",
release:2018,
rating:5,
genre:["Sci-Fi","Mystery","Western"]
}
var bloodshot={
title:"Bloodshot",
release:2020,
rating:6,
format:"digital",
genre:["Sci-Fi","Action"]
}
var revenant={
title:"Revenant",
release:2015,
rating:3,
genre:["History","Western","Action"]
}
var crisis={
title:"Crisis",
release:2016,
rating:10,
genre:["Action","Drama","Reality"]
}
var life={
title:"Life",
release:2017,
rating:9,
format:"digital",
genre:["Sci-Fi","Action","Mystery"]
}
var nmovies=new Array(fractured,life,crisis,revenant,bloodshot,countdown);
//This line outputs the title property of the first object in nmovies;
console.log(nmovies[0].title);
//this is the iteration that needs to check if an object has a format property and add it with the value 'Film'
nmovies.forEach(myfunction());
function myfunction(item, index){
//Code to check please
}
Thank you for your input.

I am new to JavaScript but hopefully that works.
function myfunction(item, index) {
if (!item.hasOwnProperty("format")) {
item.format = "Film";
}
}

Related

How to add the key of the object to the array in js

I have such objects:
robot {
id
skill
currentWorkPlace
}
warehouse {
aiStaff
currentStatus
boxes
}
I have to write a function that should add the id of a new worker to the aiStaff array, and write a reference to the warehouse object to the job in the currentWorkPlace. But I don't know how not to change the array in the warehouse.('registerRobot' function should not rewrite array 'aiStaff' inside 'warehouse' object) and I don't have to create a new variable
There is my code:
function registerRobot(robot, warehouse) {
robot.currentWorkPlace = warehouse;
robot.currentWorkPlace.aiStaff = [robot.id];
}
I dont know how to not rewrite array 'aiStaff'. Please help me Guys.
It looks like your warehouse.aiStaff is an array. In this case change your function to add the robot ID to the array:
function registerRobot(robot, warehouse) {
robot.currentWorkPlace = warehouse;
robot.currentWorkPlace.aiStaff.push(robot.id);
}
If I understood correctly you need to 'add' a new robot, but you are having the issue that the entire array gets overridden.
Considering warehouse.aiStaff is an array, if you want to add a new 'worker' you need to push the new item into the array.
function registerRobot(robot, warehouse) {
robot.currentWorkPlace = warehouse;
robot.currentWorkPlace.aiStaff.push({
id: robot.id
});
}

What is the correct way to handle this data using jQuery?

I have a list of html elements with data attributes, which I would like to assemble into a jQuery object and manipulate the values.
What is the best way to dynamically add these in an each loop so that I can easily access the data as so: data.name and data.name.prop?
I want all the naming conventions to be dynamic and based on the data.
I based my code on the top answer from here: How to create dynamically named JavaScript object properties?
So far I have:
$('.licences-list .data div').each(function(index) {
var data = {}
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
cats.push(data)
})
But when I try to iterate over the data array, like so:
$.each(cats, function(key, value){
$('<div class="card"><p>'+value+'</p></div>').appendTo('#commercial-licenses');
});
I just get [object Object] output... and I'm not sure why!
var data = {}
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
Each time you loop through, you're actually just adding an empty object (data) to your array (cats). You're then assigning a named property to that array (cats) which $.each has no idea about (it ignores them because it's iterating over an actual array).
My guess is you want an object map which is something like: var cats = { "f1": "feline 1", "f2": "feline " };
In that case what you want is:
var cats = {};
$('.licences-list .data div').each(function(index) {
cats[$(this).find('p').data('cat')] = $(this).find('p').data('catname')
})
If you want an array that contain more values than just strings (or whatever data you have added to the element), you create new objects each time and append them to the cats array:
var cats = [];
$('.licences-list .data div').each(function(index) {
cats.push({
'id': $(this).find('p').data('cat'),
'name': $(this).find('p').data('catname')
});
})
This will then give you an array that you can use $.each over, and access the values using: value.id, value.name
Don't over complicate it.
$('.div').attr('data-attribute', 'data-value');
using your example:
$('.licences-list .data div').attr('attribute-name', 'attribute-value');

JavaScript - Maintain Object key value order

My required object key-value(property-value) Order : {three:3,two:2,one:1}
I want last added key at top,When i add key-value dynamically the order i got is given below,
var numObj={};
numObj["one"]=1;
numObj["two"]=2;
numObj["three"]=3;
console.log(numObj) // result i get is { one:1, three:3,two:2 }
Please any one help me to get this key-value order {three:3,two:2,one:1}
As the commenters point out, JavaScript objects have no defined order for iteration. However, JavaScript maps do: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Map.
let aMap = new Map();
myMap.set('AKey1', 'AValue1');
myMap.set('AKey2', 'AValue2');
myMap.set('AKey3', 'AValue3');
for (let x of aMap) {
console.log(x[1]);
}
Will provide
AValue1
AValue2
AValue3

Fill observable-fields-object by same fields-names object

I have object that all of its fields are observable (knockout.observable).
I have other regular object too, that its fields have the same names like the first-object-fields.
I want to insert into each field of the first object, the value of the match-field at the second object.
For example:
var first = {
a:ko.observable(),
b:ko.observable()
};
var second= {
a:'my'
b:'fields';
};
I want the first object to look like:
first = {
a:ko.observable('my'),
b:ko.observable('fields')
};
Yes, of course, I can do it by 'each' loop.
But, my question is:
Is there any build-in function that does it?
You can use the ko.mapping plugin:
var results = ko.mapping.fromJS(second, first);
See Documentation

How can i navigate through the json?

I have some JSON which I have in a object but I can seem to return the values a sample of the json is as follows.
{
"rootLayout":"main",
"layoutDescriptions":[
{
"id":"main",
"container" : {
"type":"Tabs",
"content":[
{
"type":"Panel",
"label":"Simple Address",
"layout":"SimpleForm",
"comment":"This form is simple name value pairs",
"content":[
{ "type":"label", "constraint":"newline", "text":"Org Name" },
{ "type":"text", "property":"propOne" },
{ "type":"label", "constraint":"newline", "text":"Address" },
{ "type":"text", "property":"addrLine1" },
{ "type":"text", "property":"addrLine2" },
{ "type":"text", "property":"addrLine3" },
{ "type":"label", "constraint":"newline", "text":"Postcode" },
{ "type":"text", "property":"postcode" }
]
},
I am trying to return the rootLayout using
obj[0].rootLayout.id
This doesn't work also I am wondering how to access the content elements.
I am new to json and I have been thrown in the deep end I think. I cannot find any good reading on the internet can anyone recommend some.
Thanks.
Some explanation because you don't seem to understand JSON
It's not as complicated as one may think. It actually represents javascript objects as if they'd be written by code.
So if you have JSON written as:
{
id : 100,
name: "Yeah baby"
}
This means that your object has two properties: id and name. The first one is numeric and the second one is string.
In your example you can see that your object has two properties: rootLayout and layoutDescriptions. The first one jsonObj.rootLayout is string and will return "main" and the second one is an array:
layoutDescriptions: [ {...}, {...},... ]
Apparently an array of objects because array elements are enclosed in curly braces. This particular array element object that you provided in your example has its own properties just like I've explained for the top level object: id (string), container (another object because it's again enclosed in curlies) etc...
I hope you understand JSON notation a bit more.
So let's go to your question then
You can get to id by accessing it via:
jsonObj.layoutDescriptions[0].id
and further getting to your content objects:
var contentObjects = jsonObj.layoutDescriptions[0].container.content[0].content;
for(var i = 0; i < contentObjects.length, i++)
{
// assign this inner object to a variable for simpler property access
var contObj = contentObjects[i];
// do with this object whatever you need to and access properties as
// contObj.type
// contObj.property
// contObj.text
// contObj.constraint
}
Mind that this will only enumerate first content object's content objects... If this makes sense... Well look at your JSON object and you'll see that you have nested content array of objects.
The object is an object, not an array, and it doesn't have a property called 0.
To get rootLayout:
obj.rootLayout
However, rootLayout is a string, not an object. It doesn't have an id. The first item in the layoutDescriptions array does.
obj.layoutDescriptions[0].id
Are you trying to get one of layoutDescriptions with id equals to obj.rootLayout?
var targetLayout = {};
for(var i = 0; i < obj.layoutDescriptions.length; i++) {
if(obj.layoutDescriptions[i].id == obj.rootLayout) {
targetLayout = obj.layoutDescriptions[i]; break;
}
}
console.log(targetLayout);

Categories

Resources