It seems complicated for me.
First, I have this list:
liste_path_categories.push(
{ index: null
, letter: "letter1"
, type: key
, picture_url: "url1"
, id_categ: null
, response: "Answer here"
});
What I want is to extract from this big list an object in this form:
data["String1"]["String2"]= String3
With :
String1=list_path_categories[i].letter
String2=list_path_categories[i].id_categ
String3=list_path_categories[i].response
example:
data['A']['12'] : "A_answer"
To declare the data i make this:
var data = new Object(new Object);
How I can set all the values in data?
You can use the Array.forEach method to iterate through liste_path_categories and construct your data object.
Example:
var liste_path_categories = [];
var data = {};
liste_path_categories.push(...);
...
liste_path_categories.push(...);
liste_path_categories.forEach(function(element) {
data[element.letter] = {};
data[element.letter][element.id_categ] = element.response;
});
jsFiddle example : http://jsfiddle.net/3ZvNf/
Your question is pretty vague but do you mean something like this?
Setting a dynamic property in an object wich belongs to another object?
data['A']['12'].answer = "A_answer"
Instead of using strings, you have to use the variables in your property access:
var data = {};
if (!data[String1]) {
data[String1] = {}; // make sure that data[String1] exists and is an object
}
data[String1][String2] = String3;
If you want to do this for elements in the array, you have to iterate over the array.
P.S.: I recommend to use more expressive variable names than StringX.
first create the constructor (in OOP terminology):
var ctor_object = function(letter,id_categ,response)
{
this.letter = letter;
this.id_cated = id_categ;
this.response = response;
}
(in genereal you should omit the ctor_ syntax and name it directly after the name of the class of your object)
then use your constructor upon your list of categories:
var length = liste_path_categories.length,
element = null;
for (var i = 0; i < length; i++)
{
element = liste_path_categories[i];
my_obj = new ctor_object(element.letter,element.id_categ,element.reponse)
// Do something with my_obj
}
Related
I have an array barcodeList that stores different barcode numbers. I want to make every single one of them into a different object with the key being the barcode numbers and having different properties. Then I want to put them all into one big object foodItems. How can I do this.
Also, I realized that numbers can't be used to make variables, so I would want to put a keyword in front of them. Also, the image and ingredient values of null are just placeholders for now.
Wanted Result -
foodItems = {
Data9001: {
image : null
ingredients : null
}
Data9002: {
image : null
ingredients : null
}
}
From barcodeList = [9001, 9002]
Any recommends methods to user or keywords would be appreciated as well.
Attempted:
barcodeList.push(code)
var Food = function() {
this.image = "noImage.png"
this.nutrients = null
this.ingredients = null
}
var foodItems = {}
for (var i in barcodeList) {
//Some append function
var something = new Food()
}
To use the bracket notation to create the keys
var barcodeList = [9001, 9002];
var foodItems = {};
barcodeList.forEach(function(item){
foodItems['Data'+item] = {
image : null,
ingredients : null
};
});
console.log(foodItems);
First of all, I didn't understand, what do you mean by this
I realized that numbers can't be used to make variables
but as per your requirement, you can do something like this
var barcodeList = [9001,9002];
var foodItems = {};
for (var i = 0; i < barcodeList.length; i++) {
foodItems[barcodeList[i]] = {
image : null,
ingredients : null
}
}
console.log(foodItems)
Edited:
As per your code you can do this
var barcodeList = [9001, 9002]
var foodItems = {};
var Food = function() {
this.image = "noImage.png"
this.nutrients = null
this.ingredients = null
}
var foodItems = {}
for (var i = 0; i < barcodeList.length; i++) {
var something = new Food()
foodItems[barcodeList[i]] = something;
}
console.log(foodItems);
Not sure, how far you have gone with your answer. I would use
the Array.prototype.map() to create an array of Data objects and then use the reduce to concatenate.
Few pointers
As you need keys to begin with Data I would use ['Data'+barcode] to create them.
I will also use the ES6 spread operator to concatenate.
Here is the working code.
"use strict"
var barcodeList = [9001, 9002];
var result = barcodeList.map(function(barcode){
return {
['Data'+barcode]: {
image: null,
ingredients : null
}
}
}).reduce(function(prevValue,currValue){
return {...prevValue, ...currValue};
});
console.log ( result);
I have a job to refractor strings to start using json so they can just pass json objects. So I have made array of names and then I'm trying to go through and make key and values but I'm getting an error in the console that it cant find x of no value. Can someone point me in the right direction?
var newName = ['ManagingOrg', 'ActiveOrg', 'Severity', 'SeverityClassification', 'WorkQueue', 'TicketState',................ to long to post];
$().each(newName, function (key, value) {
key = newName[this];
value = newValues[this] = $('#' + key).val();
newArray = [key][value];
newArray = JSON.stringify(newArray);
alert(newArray);
$('.results').html(origArray[TicketNumber]);
});
I'm assuming you have "newValues" and "origArray" defined elsewhere?
In any case you'll need to at least adjust the following:
"$().each" should be $.each
"newArray" should be defined outside and you should use newArray[key] = value
you don't have a variable "TicketNumber" defined and so you should wrap "TicketNumber" in quotes
this is a reserved word so you shouldn't use it in "newName[this]" or "newValues[this]"
I suggest using a for loop instead of $.each() based on what you're trying to do inside.
https://msdn.microsoft.com/en-us/library/bb299886.aspx
var origArray = [];
var newName = ['ManagingOrg', 'ActiveOrg', 'Severity', 'SeverityClassification'
];
for (var i = 0; i < newName.length - 1; i++) {
var object = {};
object[newName[i]] = newName[i];
object = JSON.stringify(object);
origArray.push(object);
}
I tried a lot searching and didnt get desired solutions.
What I want to achieve is
var myObject {
id1 : {
name:place_name,
location : place_loc
},
id2 : {
name:place_name,
location : place_loc
},
id3 : {
name:place_name,
location : place_loc
}
}
What I want to do is that Initially I want the properties "id1", "id2".. to be dynamic. And then dynamically assign name:place_name and other properties of each property.
I dont know the number of properties (id1,id2,id3...) hence would like to add them dynamically and following the addition of properties(id1,id2... ) I want to dynamically add the property values. (place_name & place_loc) of each id.
My code looks something like this.
var myObject = {};
myObject[idnumber1].place = "SomePlace1";
myObject[idnumber1].place = "SomeLoc1";
myObject[idnumber2].place = "SomePlace1";
myObject[idnumber2].place = "SomeLoc1";
But it gives error.
I know it seems simple doubt but any help would be grateful.
Thanks in advance. :)
You are trying to set a value of already assigned objects at keys "idnumber1", etc.
What you'll need is to initialize each objects for your ids like this:
var myObject = {};
myObject[idnumber1] = {};
myObject[idnumber1].place = "SomePlace1";
myObject[idnumber2] = {};
myObject[idnumber2].place = "SomeLoc1"
I would do it this way, it's not exactly what you did ask for, but I think it will become easier to change this later on.
function Place(name, location) {
this.name = name;
this.location = location;
}
var myObject = {}
myObject['id1'] = new Place('Foo', 'Bar');
myObject['id2'] = new Place('Internet', 'test');
console.log(myObject);
To dynamically create objects in your collection, you can use a numerical counter variable to create your object collection (myObject["id" + i] = {name: place_name, location: place_loc}).
An example:
var myObject = {};
for (i = 0; i < 20; i++){
myObject["id" + i] = {name: place_name, location: place_loc}
}
In practice, you can use a counter that you increment outside of a loop.
This is the code:
var groups = {
"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}
I want to get the name value where the id is "qb45657s" how could this be accomplished? I figured the obvious loop through all of the array and check if it's equal but is there an easier way?
Edit: I cannot change "Array" to an object because I need to know the length of it for a different function.
You can simply filter on the given id:
groups["JSON"]["ARRAY"].filter(function(v){ return v["id"] == "qb45657s"; });
This will return [{"id":"qb45657s","name":"Use me."}]
Assuming you had a valid JSON string like this (note I say valid, because you need an enclosing {} or [] to make it valid):
var json = '{"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}';
You would just parse it into an actual object like this:
var jsonObj = JSON.parse(json); // makes string in actual object you can work with
var jsonArray = jsonObj.JSON.ARRAY; // gets array you are interested in
And then search for it like:
var needle = 'qb45657s';
var needleName;
for (var i = 0; i < jsonArray.length; i++) {
if (jsonArray[i].id === needle) {
needleName = jsonArray[i].name;
}
}
I'm running this code.
var output = {"records": []};
for(i = 0; i < data.length; i++)
output.records[i] = { propertyName : data[i][propertyName] }
I expected the output to be on the following form.
{ "cat" : "mjau" }
{ "dog" : "woff" }
Instead, I get to my surprise this.
{ "propertyName" : "mjau" }
{ "propertyName" : "woff" }
How can I get variable propertyName?
I'm trying to create a parser that will create a number of records that are all cat but, when called from an other place, the records should have dog property instead. I wish to avoid creating two different code pieces for that.
I've found this question, which I suspect contains the answer to my issue. However, due to ignorance, I don't get it.
Keys in object literals won't be evaluated in JavaScript. So, you need to create an empty object ({}) and then assign the key dynamically:
output.records[i] = {};
output.records[i][propertyName] = data[i][propertyName]
var a = {b:'c'}
is just like
var a = {};
a['b'] = 'c';
What you want is
a[b] = c
that is
output.records[i] = {};
output.records[i][propertyName] = data[i][propertyName];
You have in this MDN document : Working with objects.
In { propertyName : data[i][propertyName] } the property name part should be constant string. It you pass a variable it wont fetch its value.
What you have to do is
for(i = 0; i < data.length; i++){
var a = {};
a[propertyName] = data[i][propertyName];
output.records.push(a);
}
You can try this:
'"' + propertyName + '"' : ...