I am operating inside of a javascript for() loop and need to produce the following dynamically:
devCssFiles[ '../'+thisTheme._name+'/assets/css/main.css' ] =
'child_themes/'+thisTheme._name+'/master.less';
the intended result is an associative array that can be declared iteratively inside of a parent object, e.g. (thisTheme._name is declared in an external JSON file which is read when the code below is processed, this part is working fine)
var myConfigObj = {};
for ( var key in thisThemeMetaObj ) {
var devCssFiles = [],
devCssFiles[ '../'+thisTheme._name+'/assets/css/main.css' ] =
'child_themes/'+thisTheme._name+'/master.less';
myConfigObj[thisTheme._name] = devCssFiles;
}
I'm trying to give a complete explanation, but the problem is quite simple, I'm just declaring the named key of the associative array incorrectly at the line which reads devCssFiles[ '../'+thisTheme._name+'/assets/css/main.css' ] = 'child_themes/'+thisTheme._name+'/master.less';
Can someone show me the correct syntax here?
The intended output should be a JSON object like this:
myConfigObject: {
'../themeFoo/assets/css/main.css': [
'child_themes/themeFoo/master.less'
]
}
Syntax error was here:
var devCssFiles = [],
devCssFiles[ '../'+thisTheme._name+'/assets/css/main.css' ] =
'child_themes/'+thisTheme._name+'/master.less';
Problem being that devCssFiles = [] needs a semicolon (rather than a comma) so that the variable is in existence when the variable named property is declared. So it should be
var devCssFiles = [];
devCssFiles[ '../'+thisTheme._name+'/assets/css/main.css' ] =
'child_themes/'+thisTheme._name+'/master.less';
I think you want
var myConfigObj = {};
for ( var key in thisThemeMetaObj ) {
var thisTheme = thisThemeMetaObj[key],
devCssFiles = [ 'child_themes/'+thisTheme._name+'/master.less' ]; // array literal
myConfigObj['../'+thisTheme._name+'/assets/css/main.css'] = devCssFiles;
}
Notice that your devCssFiles was an array but you did create a non-numeric property on it.
Related
I have variable called obj.If i want to to have array of object i will use another variable for example:
let obj = {
name:"John"
}
let arr = [obj];
console.log(arr);
and i will get
[
{ name:"John"}
]
is there any ES6 JS shorthand for this,without using another variable ?
for example if i have only
let obj = {
name:"John"
}
how can i get
[
{ name:"John"}
]
without using another variable
hard to tell what you are asking but this would create what you created with only one variable:
let arr = [{ name:"John"}];
I am working on project where I need to maintain an array from json data returned from API, json can have tree, I have following code which is working fine but I wan to remove if conditions before assigning values to array elements
// data contains json
let newArray = []
for(let d in data){
for(let x in data[d]){
if(typeof(newArray[d]) === 'undefined'){
newArray[d] = []
}
if(typeof(newArray[d][data[d][x]['id']]) === 'undefined'){
newArray[d][data[d][x]['id']] = []
}
newArray[d][data[d][x]['id']]['price'] = data[d][x]['price']
newArray[d][data[d][x]['id']]['discount'] = data[d][x]['discount']
}
}
In above code I have to check the array first and declare it as array if its not otherwise it returns undefined error, is there any way to get rid of there conditions and extend array as per requirement ?
You can you new ES6 spread operator like this
newAraay[d] = [...newArray,...Array(data[d][x]['id']),[...Array('price',data[d][x]['price'])]]
Like here in this snippet I am directly doing abc[1][3][4] = "new value" without explicitly initialising them
let abc = [];
abc[1]= [...abc,...Array(3),[...Array(4),'new inserted value']]
console.log(abc);
newArray[d] = newArray[d] || []
You can understand this operation in this post
Or use Lodash Library
https://lodash.com/docs/4.17.11#set
I'm getting output: [{"ref":"contact.html","score":0.7071067811865475}]
$.getJSON( "index.json", function(content) {
idx = lunr.Index.load(content);
var results = idx.search(variabletosearch);
var final = JSON.stringify(results);
console.log(final);
});
How can I print value of ref? When I console.log(final[0].ref); I get undefined.
EDIT:
JSON.stringify returns a string, not an object. So in this case 'final' is a string that contains the same data that was in the object 'results'
To access the data from an object, you can use result[0].ref, or if you want to use 'final' (although you don't need to), you can do this:
final = JSON.parse(final)
console.log(final[0].ref)
If it's only one object within the array, then the other answers are enough, but since arrays are used to store multiple objects, you can do this as follows:
var arr = [
{"ref": "object1", "score": "1"},
{"ref": "object2", "score": "2"}
]
arr.map(function(object) {
console.log(object.ref)
})
JSFiddle using an alert instead of console.log()
You can also use a loop, but this cleaner.
var a = [{"ref":"contact.html","score":0.7071067811865475}];
a[0].ref;
a[0] is the '0'th (or first) element in the array which is the object literal {"ref":"contact.html","score":0.7071067811865475} from here you can access the object normally using dot notation.
Expanded out a bit:
var a = [{"ref":"contact.html","score":0.7071067811865475}];
var myObject = a[0];
console.log(myObject.ref);
//or with null checking
if (myObject) {
console.log(myObject.ref ? myObject.ref : 'no value');
}
Well, assuming
var myvar = [{"ref":"contact.html","score":0.7071067811865475}];
then:
var myref = myvar[0].ref;
Initially I have variable that contains string data
var stringArray = "[{'middleName':'T','lastName':'TEST5LAST','occupation':'QA','homeAddressZipcode':'85001','entitySequenceNumber':7,'homeAddressCity':'PHOENIX','ssn':'111111115','cellPhone':'4807363273','employer':'ABC','workPhoneExtension':'5555','entityType':'JOINT','homePhone':'4807363272','identificationType':'0','email':'FIRST5.LAST5#TEST.COM','workPhone':'4807363274','firstName':'TEST5FIRST','homeAddressStreet':'8000','homeAddressState':'AZ'}]";
Is there a function in JavaScript or AngularJS that will allow me to build a real JavaScript Array like this?:
var realArray = [
{
"middleName":"T",
"lastName":"TEST1LAST",
"occupation":"HR",
...
},
{
"middleName":"T",
"lastName":"TEST5LAST",
"occupation":"QA",
...
},
...
];
Try this.
realArray = JSON.parse(stringArray);
JSON.parse(stringArray) return JSON object
With this code,
h = {}
for (var i in [0,1]){ h[i.ToString] = i; }
I expected same result with h["1"] = 1 and h["2"] = 2.
Why is this code doesn't work, and how can I define hash key dynamically in javascript?
The for .. in loop in JS iterates over keys, not over values (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in).
So in your case, you iterate over the keys of the array you have in there.
Those will be 0, 1, 2 ... no matter what you put in there.
What you could do instead would be something like this:
var obj = {};
var data = [1,2,3,4];
data.forEach(function(val) {
obj[val] = val;
});