Automatically update JavaScript object property when another object's property is set - javascript

I have an array of objects, each containing a property named title.
The title property can hold one of two possible string values - "main" or "local". Only a single element in the array can have "main" as its title value at a given time, and the rest of the elements should have their title property set to "local".
For instance, take the following array:
var locations = [
{
title:"main",
place:"UK"
},
{
title:"local",
place:"USA"
},
{
title:"local",
place:"RUSSIA"
}
]
When setting the place:"USA" object's title property to "main", I want place:"UK" object's title property to automatically be set to "local".
How to achieve this with javascript?

One way to do this is set all title values to local, before setting desired object to main.
Another way is to remember which index is currently set to main and revert it to local when main is to be changed.

The following will return a copy of your array with the desired changes:
With ES6/Babel:
// Example:
somePlace = 'USA';
const newLocations = locations.map(l =>
{ ...l, title: l.place === somePlace ? 'main' : 'local' }
);
With Vanilla JS/Lodash:
// Example:
somePlace = 'USA';
var newLocations = _.map(locations, function (l) {
return _.assign({}, l, { title: l.place === somePlace ? 'main' : 'local' });
);

var newMainIndex = 2;
var locations = [
{
title:"main",
place:"UK"
},
{
title:"local",
place:"USA"
},
{
title:"local",
place:"RUSSIA"
}
];
for(var i=0, len=locations.length;i<len;i++){
locations[i].title = i === newMainIndex ? "main" : "local";
}

Related

assign value of a property of "clearsky" from "object" to weather so to pass through src in the image tag

The expected result is to first find weather string from array of object "objects" and then set value of "weather" variable equal to value of of clearsky value(i.e. link).
let weather = "clearsky";
const objects = [
{ "clearsky": "http://openweathermap.org/img/wn/11d#2x.png" },
{ "cloudy": "http://openweathermap.org/img/wn/19d#2x.png" },
{ "rainny": "http://openweathermap.org/img/wn/10d#2x.png" },
{ "sunny": "http://openweathermap.org/img/wn/12d#2x.png" },
];
//expected result is to first find weather string from array of object "objects" and then set value of weather equal to value of
weather = {
/* <img src={weather} alt=""/> */
};
I assume you would like to write some sort of function that displays your image corresponding to the right value (weather type) in your objects array.
I added these <img> tags (for displaying in your html).
<img id="img-clearsky">
<img id="img-rainy">
I changed the structure of your objects array a bit so that property values can be accessed in a simple way. I made a function that loops through your array and if it finds a match for your objects type, it uses the corresponding imgurl to load as src of the element with given id.
const objects = [{
"type": "clearsky",
"imgurl": "http://openweathermap.org/img/wn/11d#2x.png"
},
{
"type": "rainy",
"imgurl": "http://openweathermap.org/img/wn/10d#2x.png"
}
];
function displayImage(weatherType, elemid) {
const imgelem = document.getElementById(elemid); // Get img element by id.
// If element with given id exists.
if (imgelem !== null) {
// Loop through objects.
for (let i = 0; i < objects.length; i++) {
// Check if there is a match.
if (objects[i].type === weatherType) {
imgelem.src = objects[i].imgurl; // Fill up <img src> with corresponding url.
}
}
} else {
console.log(`No img with id: ${elemid} found.`);
}
}
// Call display with type and id.
displayImage('clearsky', 'img-clearsky');
displayImage('rainy', 'img-rainy');
There are multiple ways of doing this, but I would wrap this logic with a function - especially if you plan on splitting this into several constants.
const WeatherTypeImage = (weatherType = 'clearsky') =>
Object.assign(document.createElement('img'), {
src: {
"clearsky": "http://openweathermap.org/img/wn/11d#2x.png",
"cloudy": "http://openweathermap.org/img/wn/19d#2x.png",
"rainny": "http://openweathermap.org/img/wn/10d#2x.png",
"sunny": "http://openweathermap.org/img/wn/12d#2x.png",
}[weatherType],
alt: '',
})
document.querySelector('.js-container').appendChild(
WeatherTypeImage()
)
<div class="js-container"></div>
Or, if you would prefer to have an HTML string template:
const WeatherTypeImage = (weatherType = 'clearsky') => {
const src = {
"clearsky": "http://openweathermap.org/img/wn/11d#2x.png",
"cloudy": "http://openweathermap.org/img/wn/19d#2x.png",
"rainny": "http://openweathermap.org/img/wn/10d#2x.png",
"sunny": "http://openweathermap.org/img/wn/12d#2x.png",
}[weatherType]
return Object.assign(document.createElement('template'), {
innerHTML: `<img src="${src}" alt="">`
}).content
}
document.querySelector('.js-container').appendChild(
WeatherTypeImage()
)
<div class="js-container"></div>

Store object inside object and update

I am trying to store an array inside and object like this:
var fieldData = {
checkedItem: {
fieldID : “1234”,
SelectedFields : []
}
checkedItem: {
fieldID : “12345”,
SelectedFields : []
}
}
I then want to also replace all selected fields to this object at a later stage.
I am a newbie to this so not sure how it would be done, I have tried everything I can think of!
The later changes to the object will referenced by fieldID.
I have tried stuff like:
fieldData["fieldID"] = selectedFieldSeq;
fieldData[selectedFieldSeq]["SelectedFields"] = $('#Tree').jqxTree('getCheckedItems');
$('#Tree').jqxTree('getCheckedItems');
returns an array of checked items on my tree.
This should do it:
'fieldID = $('#Tree').jqxTree('getCheckedItems');'
'fieldData.SelectedFields = fieldID'
There is a problem with this line :
fieldData[selectedFieldSeq]["SelectedFields"]
fieldData[selectedFieldSeq] is not defined, so it's return undefined
You need to initialize it before using it :
if (!fieldData[selectedFieldSeq]) {
fieldData[selectedFieldSeq] = {
SelectedFields : []
};
}
After, you can assign some value to SelectedFields.
Or did you want to simply do this : fieldData.SelectedFields = ...; ?

Add an array to a json object in extjs

I wish to have an attribute called idField in my json object. Now this attribute is either an array if it contains multiple elements or just an object if it contains one element. I wish to create such an attribute from the data in an extjs store. In essence if the store contains just one element I need to insert this idField 'object' in the json object otherwise I need to insert an 'array' called idField in the json object. Please advise as to how to do that.
EDIT:
My store has 2 columns namely 'name' and 'type' in its data. What I wish is that if it contains just one element then my object should look like this:
{
...
idField : {
name : ...
type : ...
}
}
If my store contains 2 rows then my object should look like this :
{
...
idField : [
{
name : ...
type : ...
},
{
name : ...
type : ...
}
]
}
Also I have to INSERT this idField attribute inside the object. There is no currect idField attribute yet in the object.
EDIT 2:
I received this object in the console when I wrote console.log(Ext.getStore("My_store_name").data)
To get the data from the EXT JS store
var data = Ext.getStore("Your_Store_Name").data
In my snippet below I am assuming that you like to get the values from field name called item.
var data = Ext.getStore("Your_Store_Name").data
//imagine your JSON where you need to store is in variable myJSON
if (data.items.length == 1){
myJSON.idField = {type: 'sometype', name: data.item[0]} }
else if (data.item.length > 1)
{ //make an array of JSON
var list = [];
for(var i = 0; i < data.item.length; i++)
{
list.push({type: 'sometype', name: data.item[i]})
}
myJSON.idField = list; //set the array
}

Javascript object from string property and values

Is it possible to create a property based on string values.
I have a Json object, which used to fill the UI (select box).
"Conf" :{
"Color":[
{
"Value":"BLUE"
},
{
"Value":"GOLD"
}
],
"Size":[
{
"Value":"12"
},
{
"Value":"11"
}
],
}
Based on the selection, I need to add it to an object (Item.Conf below).
addSel provides the selection type (Color, Size etc), and the value (BLUE, 11 etc).
How can I add the selection as shown below.
So if the choice is Color : BLUE, I need to add it as Item.Conf[0].Color.Value = "BLUE"
Is it possible?
Item = {
Conf: [],
addSel: function(type, val){ //for example type="Size", val = "11"
//.... need to selection to Conf
// add a member "Size" from type string
//set its value as val
console.log(Conf[0].Size.Value) //=> 11
}
}
In essence is it possible to make an object like
"Size":{
"Value": 11
}
from strings
Your question is not entirely clear for what exactly you're trying to do, but perhaps you just need to know about using the [variable] syntax to address a property name using a string.
Example:
var x = {};
var propName = "Value";
x[propName] = 11;
This is equivalent to:
var x = {};
x.Value = 11;
But, the first form allows the property name to be a string in a variable that is not known at the time you write the code whereas the second form can only be used when the property name is known ahead of time.

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