I am getting products in JSON format and I want that my default product have a MARK that I know that is default:
DisplayValue = "MARK";
How can I do it?
In javascript you can add a property to any object just by assigning a value:
var products = [{ Name: 'A' }, { Name: 'B' }, { Name: 'C' }];
$(products).each(function() {
this.DisplayValue = "MARK" + this.Name;
}
Related
I have a question about how to get id value dynamically in an object in typescript. I can give you an example:
input object looks like this:
station = {
id: "123123",
address: {
id: "asdfasd",
type: "street"
value: "asdfas"
},
station: {
id: "asdsdfsdfasd",
type: "trainstation"
value: "asdfsdfsas"
},
information: {
id: "asdsdfsdfasd",
school: {
id: "asdsdsdsfsdfasd",
type: "middleschool"
value: "asdfssdsddfsas"
}
}
}
how can I get parent id dynamiclly, if I give a parameter such as "shool", then I can get id of information?
any solutions
Is this what are you looking for:
const station = {"id":"123123","address":{"id":"asdfasd","type":"street","value":"asdfas"},"station":{"id":"asdsdfsdfasd","type":"trainstation","value":"asdfsdfsas"},"information":{"id":"asdsdfsdfasd","school":{"id":"asdsdsdsfsdfasd","type":"middleschool","value":"asdfssdsddfsas"}}};
function getId(obj, key){
let id;
Object.keys(obj, key).forEach(x=>{
if(x == key){
id = obj[x].id; return id;
}
else{
if(typeof(obj[x]) == 'object'){ id = getId(obj[x], key)};
}
});
return id;
};
console.log(getId(station, 'school'));
With Javascript ES5, return JSON object based on tags array.
Each object have tags array and I am trying to return only the object that matches all of the tags.name.
For example, if the filter condition based on all tags name (tags[0].name , tags[1].name , tags[2].name ) is ['energy', 'video'], the return object should have tags name containing both energy and video (it can still have other tags like featured)
tags: [
{
localizedTitle: null,
title: 'Featured',
name: 'featured'
},
{
localizedTitle: null,
title: 'Video',
name: 'video'
},
{
localizedTitle: null,
title: 'Energy',
name: 'energy'
}
]
Using Array.prototype.filter(), I was able to return object that match single value -> tags[0].name
However, I need to return object based on all the tags name -> tags[0].name , tags[1].name , tags[2].name
I tried using Array.prototype.map() to combine all tags name to an array -> Array(3) [ "featured", "video", "energy" ]
And tried with Array.prototype.filter() to return object based on the new tag array but it doesn't return any object but Array []
Kindly see testing code at https://codepen.io/anon/pen/KjLKBR
I expect the output return object of
{
title: 'Video Energy Featured',
tags: [
{
localizedTitle: null,
title: 'Featured',
name: 'featured'
},
{
localizedTitle: null,
title: 'Video',
name: 'video'
},
{
localizedTitle: null,
title: 'Energy',
name: 'energy'
}
]
}
Thanks a lot in advance. Much appreciated.
You were on the right track using filter. Here is my take on your problem.
function filterItems(items, tags) {
return items.filter(function(item) {
var itemTags = item.tags.map(function (tag) { return tag.name; });
return tags.every(function(tag) { return itemTags.indexOf(tag) > -1 });
})
}
You call it with the items to filter and the list of tags. It returns the filtered list.
It is not the most optimal code, but it should do the work.
I have a complicated data structure that I need to convert to JSON. The problem is that my field names and values are in an array.
For instance, I have the following (simplified from my code base):
let SampleData = [
{ Field: 'Key', Value: '7'},
{ Field: 'City', Value: 'Some City'},
{ Field: 'Description', Value: 'Some Description'}
];
Basically my data is an array where the first element is the database column name, and the second element is the data in the column. I am trying to get a JSON object that is:
{ Key: 7, City: 'Some City', Description: 'Some Description' }
My real code has the fields and data is structures within the object, so I cannot simply use an Object.create() or Object.assign() as far as I can get working.
I have tried looping through to build a simple string and then use the JSON.parse to break it apart, but this seems like a lot of overhead for something I would have thought would be simpler.
As you asked, here's how to do it:
Mapping the array to an object
Converting the object to JSON
let array = [{
Field: 'Key',
Value: '7'
},
{
Field: 'City',
Value: 'Some City'
},
{
Field: 'Description',
Value: 'Some Description'
}
];
// #1 Mapping the array to an object...
let obj = {};
array.forEach(item => obj[item.Field] = item.Value);
// #2 Converting the object to JSON...
let json = JSON.stringify(obj);
console.log(json);
Bonus (ES6 + reduce):
const obj = array.reduce((acc, { Field, Value }) => ({ ...acc, [Field]: Value }), {});
you can try the below approach . I have used spread operator(ES6) and Object.assign to create the object ,then converted it into json string.
let SampleData = [
{ Field: 'Key', Value: '7'},
{ Field: 'City', Value: 'Some City'},
{ Field: 'Description', Value: 'Some Description'}
];
let obj = Object.assign(...SampleData.map( x => Object.values(x)).map(y => ({[y[0]]: y[1]})));
console.log(obj);
//{ Key: "7", City: "Some City", Description: "Some Description" }
console.log(JSON.stringify(obj));
I had a similar requirement and here is how I achieved it.
var ranges: segmentRange[] = new Array(2);
ranges[0] = { minimumPercentage: 50, maximumPercentage: 60 };
ranges[1] = { minimumPercentage: 30, maximumPercentage: 40 };
const segmentRanges = { segmentRanges: ranges };
return JSON.stringify(segmentRanges);
Output:
{"segmentRanges":[{"minimumPercentage":50,"maximumPercentage":60},{"minimumPercentage":30,"maximumPercentage":40}]}
HTH,
I'm using a form to edit Model. I receive data in JSON. Here's my problem:
I receive data for Checkbox only in INT: 1 or 0, I cannot change it. JSON:
{ "checkboxValue": 1 }
This field in ExtJS model is defined as INT type. Model:
{name: "checkboxValue", type: Ext.data.Types.INT},
then I set values to form this way:
formCmp.loadRecord(loadedStore.getAt(0));
and my checkbox is set correctly: when I receive 1 it's checked, 0 - unchecked.
But when I try to save record and send data to server this way:
form.updateRecord(form.getRecord());
record.save();
I need Checkbox to have also INT value - 1 or 0. But it has only BOOL value - true or false so when JSON is sent that value is NaN.
{
"checkboxValue": NaN
}
I think, that function .updateRecord(..) go through all elements and when it gets to checkbox it tries to get value, and the value is BOOL
Does anybody know how to make checkbox' output value INT?
Ext.form.Basic.updateForm uses getFieldValues method to retrieve new data for the updated record, while getFieldValues method returns only boolean values for checkboxes regardless of such properties as inputValue or uncheckedValue. So I would use convert function for the model's field to transform provided boolean value into an integer in a way like that:
Ext.define('MyModel', {
extend: 'Ext.data.Model',
fields: [
{
name: 'flag',
type: 'int',
convert: function (v, record) {
return typeof v === 'boolean' ? (v === true ? 1 : 0) : v;
}
}
],
...
});
Here is a complete jsfiddle
I think it can be done with some simple overrides
Ext.create('Ext.form.Panel', {
bodyPadding: 10,
width: 300,
title: 'Pizza Order',
items: [
{
xtype: 'fieldcontainer',
fieldLabel: 'Toppings',
defaultType: 'checkboxfield',
items: [
{
boxLabel : 'Topping?',
name : 'topping',
id : 'checkbox1',
// include these two properties in your checkbox config
uncheckedValue: 0,
setValue: function(checked) {
var me = this;
arguments[0] = checked ? 1 : me.uncheckedValue;
me.callParent(arguments);
return me;
}
}
]
}
],
renderTo: Ext.getBody()
});
I am trying to output just the hometeam name's to the page so that I can try to understand how to work with my code better. It is only printing one team to the page, and it is printing all the details of that team to the page, whereas I only want it to print one part.
This is my code, I want it to print the name's of each hometeam to the page
app.get('/home', function(req, res) {
Match.findOne({}).populate('hometeam.name').exec(function(err, teams){
util.log(teams);
res.send(teams);
});
});
But when I load the page all I get is the first piece of data from this list of Matches
[
{
"hometeam": "5106e7ef9afe3a430e000007",
"_id": "5113b7ca71ec596125000005",
"__v": 0,
"key": 1360246730427
},
{
"hometeam": "5113c13e0eea687b28000001",
"_id": "5113e951354fe70330000001",
"__v": 0,
"key": 1360259409361
},
{
"hometeam": "5113c13e0eea687b28000001",
"_id": "5113e999354fe70330000002",
"__v": 0,
"key": 1360259481412
}
]
Also, if I try to put util.log(teams.hometeam.name) I get the following:
TypeError: Cannot call method 'toString' of undefined
But I would want it to be able to print the name which belongs to hometeam here. As hometeam is just the objectId of a Team in my database, am I missing something with the DBreferencing here?
Update:
Team Schema
var Team = new Schema({
'key' : {
unique : true,
type : Number,
default: getId
},
'name' : { type : String,
validate : [validatePresenceOf, 'Team name is required'],
index : { unique : true }
}
});
module.exports.Schema = Team;
module.exports.Model = mongoose.model('Team', Team);
Match Schema
var Team = require('../schemas/Team').Schema;
var Match = new Schema({
'key' : {
unique: true,
type: Number,
default: getId
},
'hometeam' : { type: Schema.ObjectId, ref: 'Team' },
'awayteam' : { type: Schema.ObjectId, ref: 'Team' }
});
module.exports = mongoose.model('Match', Match);
Populate takes the property name of the property you are trying to retrieve. This means that you should use 'hometeam' instead of 'hometeam.name'. However, you want to retrieve the name of the team so you could filter for that. The call would then become..
Match.findOne({}).populate('hometeam', {name: 1}).exec(function(err, teams)
Now you have a property called 'hometeam' with in that the name. Have fun :)
EDIT
Showing how to have a single mongoose instance in more files to have correct registration of schemas.
app.js
var mongoose = require('mongoose');
var Team = require('./schemas/team-schema')(mongoose);
var Match = require('./schemas/match-schema')(mongoose);
// You can only require them like this ONCE, afterwards FETCH them.
var Team = mongoose.model('Team'); // LIKE THIS
schemas/match-schema.js
module.exports = function(mongoose) {
var Match = new mongoose.Schema({
'key' : {
unique: true,
type: Number,
default: getId
},
'hometeam' : { type: mongoose.Schema.ObjectId, ref: 'Team' },
'awayteam' : { type: mongoose.Schema.ObjectId, ref: 'Team' }
});
return mongoose.model('Match', Match);
};
schemas/team-schema.js
module.exports = function(mongoose) {
var Team = new mongoose.Schema({
'key' : {
unique : true,
type : Number,
default: getId
},
'name' : { type : String,
validate : [validatePresenceOf, 'Team name is required'],
index : { unique : true }
}
});
return mongoose.model('Team', Team);
};