var ce_info=[
{location:"inchannel",name:"Jae Jung",volume:"50",url:"img/jae.jpeg",group:1},
{location:"inchannel",name:"Houston",volume:"50",url:"img/houston.jpeg",group:1},
{location:"inchannel",name:"Jun kuriha..",volume:"50",url:"img/jun.jpeg",group:1},
{location:"inchannel",name:"Andrea Melle",volume:"50",url:"img/andrea.jpeg",group:0},
{location:"inchannel",name:"Tomoaki Ohi..",volume:"50",url:"img/ohira.jpeg",group:0},
{location:"inchannel",name:"Woosuk Cha..",volume:"50",url:"img/woosuk.jpeg",group:0},
{location:"inchannel",name:"Luca Rigaz..",volume:"50",url:"img/luca.jpeg",group:0},
{location:"inchannel",name:"SooIn Nam",volume:"50",url:"img/sooin.jpeg",group:0}
];
var inch_info=[{location:"ichat",name:"",volume:"50",url:""}];
for(i=0;i<ce_info.length;i++)
{
if(ce_info[i].location=="inchat")
{
inch_info[inchat_count].name=ce_info[i].name;
inch_info[inchat_count].url=ce_info[i].url;
inchat_count++;
}
}
I am trying to copy ce_info to inch_info.
It seems like it does not work.It occurs an error when I try to copy ce_info to inch_info
Any thought?
Copying a native JS Array is easy. Use the Array.slice() method which creates a copy of part/all of the array.
var foo = ['a','b','c','d','e'];
var bar = foo.slice();
now foo and bar are 5 member arrays of 'a','b','c','d','e'
inchat_count seems to be uninitialized.
var inch_info=[{location:"icha",name:"",volume:"50",url:""}];
var inchat_count = 0; // You forgot this line!!
for(i=0;i<ce_info.length;i++)
{
if(ce_info[i].location=="inchat")
{
inch_info[inchat_count].name=ce_info[i].name;
inch_info[inchat_count].url=ce_info[i].url;
inchat_count++;
}
}
You still have a typeO in your code
var inch_info=[{location:"ichat",name:"",volume:"50",url:""}];
shouldnt location be inchat instead of ichat? Because that is what you check for in this line
if(ce_info[i].location=="inchat")
Furthermore in ce_info there is no location named inchat so the result of this piece of code will not be executed. But if there where an element in ce_info that has the location inchat this will be the code you need to add the location and name to the inch_info array.
Change your for loop in this:
for(var eElem in ce_info)
{
if(ce_info[eElem].location=="inchannel")
{
var temp = {};
temp.name=ce_info[eElem].name;
temp.url=ce_info[eElem].url;
inch_info.push(temp);
}
}
using jQuery you can achieve it so easily:
See a working demo here
following jQuery code makes sure that you do not have a by reference object of ce_info.
jQuery code:
var inch_info= jQuery.extend(true, {}, ce_info);
alert("inch_info: before changing text: "+inch_info[0].location);
inch_info[0].location = "hello world"
alert("inch_info: after changing text: "+inch_info[0].location);
alert("ce_info: after changing text: "+ce_info[0].location);
Related
Hi there before I start I did try looking through the search about writing variables so if this has been asked and answered then I do apologise but this is baffling me ....
So here goes ..
example of what I am talking about
var i = e[ab]
var n = e[cd][ef]
var t = e[cd][gh]
I know that when I want var i I can put e.ab but how would I go about writing var n and var t
So assuming your object looks like this (based on your description, it sounds like you want to access an object which is the property of another object), and you want to access them through the indexer properties (which would be a property of a property).
var e = {
ab : "variableOne",
cd : {ef:"ef object"},
gh : {ij:"ij object"},
}
var i = e["ab"]
//if these are properties, then you need to add quotes around them
//to access a property through the indexer, you need a string.
var n = e["cd"]["ef"]
var t = e["gh"]["ij"]
console.log(i);
console.log(n);
console.log(t);
console.log("this does the same thing:")
console.log(e.ab);
console.log(e.cd.ef);
console.log(e.gh.if);
In your example the object would look like
//e is the parameter, but I show it as a variable to show
// it's relation to the object in this example.
e = {
now_playing: {artist:"Bob Seger"; track:"Turn the Page"}}
}
this is different than an array of arrays:
var arr = [
['foo','charlie'],
['yip', 'steve'],
['what', 'bob', 'jane'],
];
console.log(arr[0][0]); //foo
console.log(arr[0][1]); //charlie
console.log(arr[1][0]); //yip
console.log(arr[1][1]); //steve
console.log(arr[2][2]); //jane
https://jsfiddle.net/joo9wfxt/2/
EDIT:
Based on the JSON provided, it looks like parameter e in the function is assigned the value of the item in the array. With your code:
this line will display: "Rock you like a hurricane - Nontas Tzivenis"
$(".song_title .current_show span").html(e.title);
and this line will display: "Rascal Flatts - Life is a Highway".
$(".song_title .current_song span").html(e.np);
If it's not displaying you might want to double check your JQuery selectors. This ".song_title .current_song span" is selecting it by the classes on the element.
I think you are in need of a bit of a refresher on basic JavaScript syntax. Here's how you can assign an "empty object" to a variable, then start to assign values to it's properties:
e = {}
e.ab = {}
e.cd = {}
e.cd.ef = "data"
or you can use the associative array syntax for property access:
e = {}
e["ab"] = {}
e["cd"] = {}
e["cd"]["ef"] = "data"
You see the latter is using the object e like a two-deep associative array. Is that what you are looking to do?
JavaScript is not strongly typed. So an Array "a" could contain objects of different types inside.
var a = [ "a value", [1, 2, 3], function(){ return 5 + 2;}];
var result = a[0]; //get the first item in my array: "a value"
var resultOfIndexedProperty = a[1][0]; //Get the first item of the second item: 1
var resultOfFunc = a[2](); //store the result of the function that is the third item of my array: 7
Hope this helps a little.
I am building JavaScript code to make a custom push function. My new function should act exactly like the original push function.
Here is the code. Please check it.
<script type="text/javascript">
function MyArray(){
this.add=function(x){
return this[this.length]=x;
}
}
MyArray.prototype=Array.prototype;
var collection = new MyArray();
collection.push(44);
collection.add(56); // this is not working.
collection.push(77);
collection.push(88);
console.log(collection);
</script>
Because you're not using a native array, the length property doesn't automatically adjust itself. You need to increment it manually, otherwise the next push will just overwrite it:
function MyArray(){
this.add=function(x){
return this[this.length++]=x;
}
}
If you want to use add instead of push (so, use add as push-alias), just refer to the original Array.prototype.push. See snippet. The snippet also contains a custom addMulti method, derived from Array.prototype.push.
function MyArray(){ }
MyArray.prototype = Array.prototype;
MyArray.prototype.add = Array.prototype.push;
// custom addMulti method, derived from Array.prototype.push
MyArray.prototype.addMulti = function addMulti(arrayOfValues){
[].push.apply(this, arrayOfValues);
};
var foo = new MyArray;
// add and push both work
foo.add(13);
foo.push(17);
foo.add(15,16,18);
foo.push(112);
// push an array of values
foo.addMulti([200,300,400,500]);
var report = new MyArray;
report.add('<code>foo.length: ',foo.length, ', foo: [', foo, ']</code>');
document.querySelector('#result').innerHTML = report.join('');
<div id="result"><div>
I have an object which comes back as part of a return data from a REST server. It is part of an item object.
(I don't have control over the REST server so I can't change the data received):
{
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
What I want to end up with is some control over this, so that I can display the results when a product is selected in my app. It will appear in a modal. I am using Marionette/Backbone/Underscore/JQuery etc. but this is more of a JavaScript question.
I have tried multiple ways of getting at the data with no success. I would like to be able to have the options in a nested array, but I'd be open to other suggestions...
Basically this kind of structure
var Color=('Red', 'Green', 'Blue', 'Orange')
var Size('Small', 'Medium', 'Large')
The Object structure is fine, just need to be able to translate it to an array and take out the 'Option' keyword
Important to mention that I have no idea what the different options might be when I receive them - the bit after Options: might be any form of variation, color, size, flavour etc.
Loop through the parsed JSON and create new keys on a new object. That way you don't have to create the var names yourself; it's automatically done for you, albeit as keys in a new object.
var obj = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
}
function processObj() {
var newObj = {};
for (var k in obj) {
var key = k.split(':')[1].toLowerCase();
var values = obj[k].split(',');
newObj[key] = values;
}
return newObj;
}
var processedObj = processObj(obj);
for (var k in processedObj) {
console.log(k, processedObj[k])
// color ["Red", "Green", "Blue", "Orange"], size ["Small", "Medium", "Large"]
}
Edit: OP I've updated the code here and in the jsfiddle to show you how to loop over the new object to get the keys/values.
Fiddle.
var json = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var color = json['Option:Color'].split(',');
var size = json['Option:Size'].split(',');
Try this to do get a solution without hardcoding all the option names into your code:
var x = {
"Option:Color":"Red,Green,Blue,Orange",
"Option:Size":"Small,Medium,Large"
};
var clean = {};
$.each(x, function(key, val){ //iterate over the options you have in your initial object
var optname = key.replace('Option:', ''); //remove the option marker
clean[optname] = val.split(","); //add an array to your object named like your option, splitted by comma
});
clean will contain the option arrays you want to create
EDIT: Okay, how you get the names of your object properties like "color", which are now the keys in your new object? Thats the same like before, basically:
$.each(clean, function(key, val){
//key is the name of your option here
//val is the array of properties for your option here
console.log(key, val);
});
Of course we stick to jQuery again. ;)
I would like to be able to reference an array by using a string, as such:
var arrayName = "people";
var people = [
'image47.jpeg',
'image48.jpeg',
'image49.jpeg',
'image50.jpeg',
'image52.jpeg',
'image53.jpeg',
'image54.jpeg',
'image55.jpeg',
]
function myFunc (arrayName)
{
//arrayName is actually just a string that evaluates to "people", which then in turn would reference the var people, which is passed in.
}
Any thoughts on how to do this? Sorry if I'm missing something obvious.
You can simply create a global dictionary, like this:
var people = ['image47.jpeg', 'image48.jpeg'];
var cars = ['image3.png', 'image42.gif'];
var global_arrays = {
people: people,
cars: cars
};
function myFunc(arrayName) {
var ar = global_arrays[arrayName];
// Do something with ar
}
Note that the first line of myFunc makes it clear that this is just a complicated way of having myFunc accept the array itself in the first place. I strongly suggest that you do just that, like this:
function myFunc(ar) {
// Do something with ar
}
myFunc(people);
This means that your code will be reusable by anyone else (say, a third-party plugin that wants to render giraffes) and not require any global variables.
If your array is declared outside of a function, you can access it using the this keyword like so:
function myFunc(arrayname) {
var itemzero = this[arrayname][0];
}
var arrayName = "people";
var people = [
'image47.jpeg',
'image48.jpeg',
'image49.jpeg',
'image50.jpeg',
'image52.jpeg',
'image53.jpeg',
'image54.jpeg',
'image55.jpeg',
]
function myFunc (arrayName)
{
//Here you can use this or window obj To quote you array.
//such as window[arrayName]
}
I have the following array:
var example = [
function() { /* hello */ },
function() { /* goodbye */ }
];
I use delete example[0]; and am left with the following result:
var example = [
1: function() { /* goodbye */ }
];
Is there a better solution than delete? Or is there a simple way to fix the indexes in the array? (I have jQuery at my disposal)
Edit: I fixed the example array. The indexes were there for the example.
As example is an array, instead of delete, you can use .splice [MDN]:
example.splice(0, 1);
But if examples is actually an object, you'd have to use delete and iterate over all properties and "rename" them. Though it's probably easier to use an array instead.
The reason why you get this result with delete is that you are removing the property '0' from the underlying object and the property '1' still exists. You are basically operating on a lower level.
Another problem with gaps in the indexes is that array.length will always return the the highest index + 1 and not the actual number of values in the array. So after deleting the element, example.length would still be 2.
Your way of defining an array is wrong.
This is how its done:
var example = [
function() { /* hello */ },
function() { /* goodbye */ }
];
you can use shift to remove the first element:
var firstElement = example.shift();
You could use a custom sort function:
array.sort(sortfunction)
function sortfunction(a, b){
// check indexes here
}
You can just shift your first element.
http://jsfiddle.net/4zW7B/1/
var example = [
function() { alert('hello'); },
function() { alert('goodbye'); }
];
example[0]();
example.shift();
example[0]();