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 + '"' : ...
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);
}
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
}
Here is my response code in jQuery:
var response = $.parseJSON(response);
for (var i = 0; i < response.groupIds.length; i++) {
console.log(response.groupIds[i], i);
}
Each response.groupIds[i] is of the form {"unknown name":"unknown value"}.
I wish to access both of these bits of data in javascript, how do I accomplish this when I don't know in advance what e.g. unknown name is?
Use Object.keys to retrieve a full list (array) of key names. A polyfill is available here.
var group = response.groupIds[i];
var allPropertyNames = Object.keys(group);
for (var j=0; j<allPropertyNames.length; j++) {
var name = allPropertyNames[j];
var value = group[name];
// Do something
}
Your question's response format contains only one key-value pair. The code can then be reduced to:
var group = response.groupIds[i];
var name = Object.keys(group)[0]; // Get the first item of the list; = key name
var value = group[name];
If you're not interested in the list, use a for-i-in loop with hasOwnProperty. The last method has to be used, to exclude properties which are inherit from the prototype.
for (var name in group) {
if (group.hasOwnProperty(name)) {
var value = group[name];
// Do something
}
}
Use a for..in loop:
for( x in response.groupIds[i]) {
// x is now your unknown key
// response.groupIds[i][x] is the unknown value
}
Since there is only one property of the object, that'll work nicely.
I'm currently using javascript eval() to check and create a multidimensional object that I have no idea of the depth.
Basically, I want to know if there's any way to create this multi-depth object. The object can be as deep as result['one']['two']['three']['four']['five']['six']['seven']. I know there are cases where using eval() is perfectly fine, but I'm also worried about performance. I thought about referencing each depth to a new variable, but I don't know how to do pointers in Javascript
create = function(fields, create_array){
var field;
for (j = 0; j < len; j++){
field = fields.slice(0, j).join('');
if (field){
// is there any way to do this without eval?
eval('if (typeof result' + field + ' == "undefined" || !result' + field + ') result' + field + ' = ' + (create_array?'[]':'{}') + ';');
}
}
}
How about
var deep = { one: { two: { three: { four: { five: { six: { seven: 'peek-a-boo!' }}}}}}};
I don't see what "eval()" has to do with this at all; there's no reason to "initialize" such an object. Just create them.
If you wanted to write a function with an API like you've got (for reasons I don't understand), you could do this:
function create(fields, create_array) {
var rv = create_array ? [] : {}, o = rv;
for (var i = 0; i < fields.length; ++i) {
o = o[fields[i]] = create_array ? [] : {};
}
return rv;
}
There doesn't seem to be any point to the "create_array" flag, since you're presumably always using strings for keys.
Never mind, found my way in. I used a recursive function to ensure that the object was created properly.
create = function(create_array, res, path){
var field = fields.shift();
if (field){
if (typeof res[field] == "undefined" || !res[field]) res[field] = (create_array?[]:{});
path.push('["' + field + '"]');
create(create_array, res[field], path);
}
}
var result = {}, strpath = [], fields[];
create(true, result, strpath);
eval('result' + strpath.join('') + ' = value;');
being variable "field" a variable outside the function, that contained the levels of the object. doing result["field"]["name"]["first"] = value without the ["field"] or ["name"] field existing or defined as an object, would throw an error and stop execution, that's why I'm pre-creating the object variable, either as an array or object.
I couldn't find another option for the second eval() though. There's no way to provide a way to access multiple properties on an object without knowing the depth.