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);
Related
I have this String:
['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
I want to get the keys 'TEST1-560' which is always fist and "car" value.
Do you know how I can implement this?
This is a very, very scuffed code, but it should work for your purpose if you have a string and you want to go through it. This can definitely be shortened and optimized, but assuming you have the same structure it will be fine.:
// Your data
var z = `['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']`;
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1,dividedVar[ind].split(":")[1].split("}")[0].length-1);
console.log(car)
}
}
console.log(testName);
output:
BLUE
TEST1-560
In a real application, you don't need to log the results, you can simply use the variables testName,car. You can also put this in a function if you want to handle many data, e.g.:
function parseData(z) {
var testName = z.substring(2).split("'")[0];
var dividedVar = z.split(",");
for (var ind in dividedVar) {
if (dividedVar[ind].split(":")[0] === '"car"') {
var car = dividedVar[ind].split(":")[1].split("}")[0].substring(1, dividedVar[ind].split(":")[1].split("}")[0].length - 1);
}
}
return [testName, car]
}
This will return the variables values in an array you can use
const arr = ['TEST1-560', '{"data":[{"price":0.0815,"volume":0.2,"car":"BLUE"}],"isMasterFrame":false}']
const testValue = arr[0];
const carValue = JSON.parse(arr[1]).data[0].car;
console.log(testValue);
console.log('-----------');
console.log(carValue);
If your structure is always the same, your data can be extracted like above.
I'm pretty new (a few weeks in) to js and have a question about an incremental game I'm developing. My issue has to do with creating an array from an object I have and then fetching a property of the object, which is used in a compare statement and updated in my HTML.
I have the following object called UPGRADES:
var UPGRADES = {
newClothes: {
name: "New Clothes",
desc: "Give your bums a new look and some more motivation! \n Bum
production bonus: 100%",
moneyCost: 1000,
scienceCost: 10,
requiredScience: 10,
buildingAffected: BUILDINGS.bumBuilding,
upgVal: 2,
id: 'newClothes'
},
//{upgrade 2}
//{upgrade 3 etc.}
}
For one part of my code I need to go through each element of UPGRADES, return the nth object WITHIN "upgrades" (with newClothes as index 0), and then call (Nth index.scienceCost).
So far I've done the following:
var numBuildings = objectLength(BUILDINGS);
var numUpgrades = objectLength(UPGRADES);
function checkVisiblityOnUpgrades () {
var upgArray = [];
for (var a = 0; a < numUpgrades; a++) {
upgArray[a] = Object.keys(UPGRADES)[a].toString();
console.log(UPGRADES.upgArray[a]);
if (UPGRADES.upgArray[a].requiredScience <= resources.science) {
var idString = upgArray[a].id.toString();
getId(idString.concat("Button")).style.visibility = "visible";
getId(idString.concat("MoneyCostDisp")).innerHTML =
numFormat(upgArray[a].moneyCost);
getId(idString.concat("ScienceCostDisp")).innerHTML =
numFormat(upgArray[a].scienceCost);
}
}
}
I get this error along with it:
Uncaught TypeError: Cannot read property '0' of undefined
at checkVisiblityOnUpgrades (game.js:268)
at update (game.js:290)
268 is console.log(UPGRADES.upgArray[a]);
I was wondering how I would actually go about grabbing the values of the object I wanted. I'm creating an array in checkVisibilityOnUpgrades() so I can iterate through each upgrade with a for loop.
Another question I have is: If I was going to store 100+ instances of upgrades, would it be better to switch UPGRADES to an array rather than its own object? That way I could grab values a lot more easily.
You can drastically simplify your initial logic there with Object.entries:
Object.entries(UPGRADES).forEach(({ key, thisUpgradeObject }) => {
// `key` references the outer property, eg., 'newClothes'
// `thisUpgradeObject` references the inner object
});
So
Object.entries(upgArray).forEach(({ key, obj }) => {
const {
requiredScience,
id,
moneyCost,
scienceCost,
} = obj;
if (requiredScience < resources.science) return;
const idString = id.toString();
getId(idString.concat("Button")).style.visibility = "visible";
getId(idString.concat("MoneyCostDisp")).innerHTML = numFormat(moneyCost);
getId(idString.concat("ScienceCostDisp")).innerHTML = numFormat(scienceCost);
});
I see the problem here:
You create an array called upgArray, but then try to access UPGRADES.upgArray which is undefined. What you want to write there is likely UPGRADES[upgArray[a]].
function checkVisiblityOnUpgrades () {
var upgArray = Object.keys(UPGRADES);
for (var a = 0; a < numUpgrades; a++) {
if (UPGRADES[upgArray[a]].requiredScience <= resources.science) {
var idString = UPGRADES[upgArray[a]].id.toString();
getId(idString.concat("Button")).style.visibility = "visible";
getId(idString.concat("MoneyCostDisp")).innerHTML =
numFormat(UPGRADES[upgArray[a]].moneyCost);
getId(idString.concat("ScienceCostDisp")).innerHTML =
numFormat(UPGRADES[upgArray[a]].scienceCost);
}
}
}
I have the following array that contains user data. There are only about 20 elements in thsi data. I get this from my server and it is stored locally:
var userdata1 =
[
{"id":"527ddbd5-14d3-4fb9-a7ae-374e66f635d4","name":"xxx"},
{"id":"e87c05bc-8305-45d0-ba07-3dd24438ba8b","name":"yyy"}
]
I have been using the following function to get the user name from my userProfiles array.
$scope.getUser = function (userId) {
if (userId && $scope.option.userProfiles)
for (var i = 0; i < $scope.option.userProfiles.length; i++)
if ($scope.option.userProfiles[i].id === userId)
return $scope.option.userProfiles[i].name;
return '';
}
I was looking for a more efficient way to get the name so I asked this question:
How can I check an array for the first occurence where a field matches using _lodash?
Now I am wondering. Is there another way that I could store my data to make it easier to access? One person suggested this
in the comments:
var usersdata2 = {someuserid: {id: "someusersid", name: 'Some Name'},
anotheruserid: {id: "anotheruserid", name: 'Another Name'}};
If I was to do this then would it be more efficient, how could I change my data from the first form userdata1 into userdata2
and how could I access it?
You can transform your array as follows:
var userMap = userdata1.reduce(function(rv, v) {
rv[v.id] = v;
return rv;
}, {});
That will give you an object that maps the "id" values onto the original object. You would then access the values like this:
var someUser = userMap[ someUserId ];
This set up will be much more efficient than your array, because finding an entry takes an amount of time proportional to the size of the "id" strings themselves (plus a little). In your version, you have to search through (on average) half the list for each lookup. For a small set of records, the difference would be unimportant, but if you've got hundreds or thousands of them the difference will be huge.
The .reduce() function is not available in older browsers, but there's a fill-in patch available on the MDN documentation site:
// copied from MDN
if ('function' !== typeof Array.prototype.reduce) {
Array.prototype.reduce = function(callback, opt_initialValue){
'use strict';
if (null === this || 'undefined' === typeof this) {
// At the moment all modern browsers, that support strict mode, have
// native implementation of Array.prototype.reduce. For instance, IE8
// does not support strict mode, so this check is actually useless.
throw new TypeError(
'Array.prototype.reduce called on null or undefined');
}
if ('function' !== typeof callback) {
throw new TypeError(callback + ' is not a function');
}
var index, value,
length = this.length >>> 0,
isValueSet = false;
if (1 < arguments.length) {
value = opt_initialValue;
isValueSet = true;
}
for (index = 0; length > index; ++index) {
if (this.hasOwnProperty(index)) {
if (isValueSet) {
value = callback(value, this[index], index, this);
}
else {
value = this[index];
isValueSet = true;
}
}
}
if (!isValueSet) {
throw new TypeError('Reduce of empty array with no initial value');
}
return value;
};
}
Try something like this:
var usernames = {};
userdata1.forEach(function(u) {usernames[u.id] = u.name;});
alert(usernames[userId]);
(You'll either need a shim or a manual for loop to support older browsers - the above is intended to just give you an idea on how you can simplify your access)
To make the access by ID more efficient copy the data into an object:
var userdata1 =
[
{"id":"527ddbd5-14d3-4fb9-a7ae-374e66f635d4","name":"xxx"},
{"id":"e87c05bc-8305-45d0-ba07-3dd24438ba8b","name":"yyy"}
];
var userIdMap = {};
for (var i = 0; i < userdata1.length; i++) {
var item = userdata1[i];
userIdMap[item.id] = item;
}
which means the function is now:
$scope.getUser = function (userId) {
if (userId && $scope.option.userProfiles) {
var user = userIdMap[userId];
if(user)
return user.name;
}
return '';
}
Here is a function that puts your array items into a lookup object:
function arrayToLookup(array, idProperty) {
var result = {};
for (var i = array.length - 1; i >= 0; i--) {
result[array[i][idProperty]] = array[i];
}
return result;
}
Usage would be like this, for your example:
var userdata1 =
[
{"id":"527ddbd5-14d3-4fb9-a7ae-374e66f635d4","name":"xxx"},
{"id":"e87c05bc-8305-45d0-ba07-3dd24438ba8b","name":"yyy"}
]
// create a lookup object of your array.
// second parameter is the name of the property to use as the keys
var userDataLookup = arrayToLookup(userdata1, 'id');
// this is how you get a specific user out of the lookup
var user = userDataLookup["527ddbd5-14d3-4fb9-a7ae-374e66f635d4"];
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
}
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 + '"' : ...