How to loop over an array within a JavaScript object? - javascript

Very new to JavaScript objects, so I am not to sure how to go about doing this.
Within my object, I have an array called myArray. I am attempting to loop over it to print out everything on the page. Usually there is a a lot more data within the object, but it has been removed for this example.
This is my object:
var data = [
{
myArray:
{
name: 'name1',
code: 'code1',
data: {
date: '20-Apr-2014',
signal: 'signal1'
}
},
{
name: 'name2',
code: 'code2',
data: {
date: '21-Apr-2014',
signal: 'signal2'
}
}
}
]
This is my iteration code:
var arrayLength = data.myArray.length - 1;
for (var i = 0; i <= arrayLength; i++) {
var name = data.myArray[i].name;
console.log(name);
}
My code above should produce the results in the console name1 and name2. However, I am getting an error of Cannot read property 'length' of undefined.
How can I change my above code to do this?

Your object should use brackets for the array:
var data = {
myArray: [
{
name: 'name1',
code: 'code1',
data: {
date: '20-Apr-2014',
signal: 'signal1'
}
},
{
name: 'name2',
code: 'code2',
data: {
date: '21-Apr-2014',
signal: 'signal2'
}
}
]
}
I've also removed the outermost brackets, since it would appear from your question that your intent was to have a single array inside an object, and not an array of arrays.
With the object above, your iteration code will work fine.

Related

Javascript How to push item in object

var data = {items: [
{id: "1", name: "Snatch", type: "crime"}
]};
And I would like to add the mark's key.
So the result would be:
var data = {items: [
{id: "1", name: "Snatch", type: "crime", mark:"10"}
]};
How can I do ?
I tried to do data.items.push({"mark": "10"}) but it adds another object which is not what I want.
Thanks.
Access the correct index and simply set the property
data.items[0].mark = "10";
You may not need push here because you want to create a new key to n existig object. Here you need dot (.) to create a new key
var data = {
items: [{
id: "1",
name: "Snatch",
type: "crime"
}]
};
data.items[0].mark = "10";
console.log(data)
And, if you want add “mark” property to all the items:
data.items.forEach(function(item, index) {
data.items[index].mark = 10;
}

json object from javascript nested array

I'm using a nested array with the following structure:
arr[0]["id"] = "example0";
arr[0]["name"] = "name0";
arr[1]["id"] = "example1";
arr[1]["name"] = "name1";
arr[2]["id"] = "example2";
arr[2]["name"] = "name2";
now I'm trying to get a nested Json Object from this array
arr{
{
id: example0,
name: name00,
},
{
id: example1,
name: name01,
},
{
id: example2,
name: name02,
}
}
I tought it would work with JSON.stringify(arr); but it doesen't :(
I would be really happy for a solution.
Thank you!
If you are starting out with an array that looks like this, where each subarray's first element is the id and the second element is the name:
const array = [["example0", "name00"], ["example1", "name01"], ["example2", "name02"]]
You first need to map it to an array of Objects.
const arrayOfObjects = array.map((el) => ({
id: el[0],
name: el[1]
}))
Then you can call JSON.stringify(arrayOfObjects) to get the JSON.
You need to make a valid array:
arr = [
{
id: 'example0',
name: 'name00',
},
{
id: 'example1',
name: 'name01',
},
{
id: 'example2',
name: 'name02',
}
];
console.log(JSON.stringify(arr));
Note that I am assigning the array to a variable here. Also, I use [] to create an array where your original code had {}.

JS – How to build a dynamic nested object of arrays with objects etc. from string

This is a nice evening project, but actually i'm stuck with some headache.
All I need is a function like this example:
result = set("itemCategories[0].items[0].name", "Test")
which should return:
{ itemCategories: [
{
items: [ {name: "Test"} ]
}
}]
...and in case of the given attribute "itemCategories[1].items[2].name" this result:
{ itemCategories: [
null,
{
items: [
null,
null,
{name: "Test"}
]
}
}]
Use lodash#set:
result = lodash.set({}, "itemCategories[0].items[0].name", "Test")
If you are asking about the vanilla JavaScript Set method then you could do this.
/* this is what you are trying to get.
{ itemCategories: [
{
items: [ {name: "Test"} ]
}
}]
*/
var mySet = new Set(); // your set object.
Create your data (number, text, string, object, array, null).
ver data1 = 365;
ver data2 = 'Dragonfly';
ver data3 = {name: 'Bobby', age: 20000, job: 'dj'};
Then you just add to that set using its add method.
mySet.add(data1);
mySet.add(data2);
mySet.add(data3);
So to get what you are looking for you would write this.
var itms = {items: [{name: 'test'}]};
mySet.add(itms);
The good thing about set is that is like an array. So you can use forEach.
mySet.forEach( function(val){
console.log(val); // gets all your data.
});
You can even check if a value is in your data using the has method.
mySet.has(365); // true
mySet.has(36500000); as false
JavaScript Set

Is possible to rewrite all values in array without for loop in javascript?

Let's suppose that we have an array (myArray) with data like this:
0: myArray
content: 'something'
date: '15.5.2015'
name: 'Abc'
1: myArray
content: 'text'
date: '15.5.2015'
name: 'Bla'
2: etc ...
Now for rewriting all values (into e.g. empty string) of one object properties in this array (for example: 'content') I would use for loop like this:
for(var i = 0; i < myArray.length; i++){
myArray[i].content = '';
}
So result of this would be:
0: myArray
content: ''
date: '15.5.2015'
name: 'Abc'
1: myArray
content: ''
date: '15.5.2015'
name: 'Bla'
2: etc ...
My question is: Is possible to do same result without using loop in javascript? Something like this:
myArray[all].content.RewriteInto('');
Tnx for ideas.
Anything you do will end up looping in some fashion. However, you don't have to loop...
because we now have functional array methods! You're probably looking for map or reduce, perhaps both, since you want to transform (map) each element and/or combine them into one (reduce).
As an example, we can take your data and return a string with all of the content fields concatenated using:
var data = [{
content: 'something',
date: '15.5.2015',
name: 'Abc'
}, {
content: 'text',
date: '15.5.2015',
name: 'Bla'
}];
var result = data.map(function(it) {
return it.content;
}).join(' ');
document.getElementById('r').textContent = JSON.stringify(result);
<pre id="r"></pre>
To remove the content field from each item, without modifying the input, you can:
var data = [{
content: 'something',
date: '15.5.2015',
name: 'Abc'
}, {
content: 'text',
date: '15.5.2015',
name: 'Bla'
}];
var result = data.map(function(it) {
return {date: it.date, name: it.name};
});
document.getElementById('r').textContent = JSON.stringify(result);
<pre id="r"></pre>
You should look at the map function.
Use it like this :
myArray.map(function (data) {
return data.content = 'value';
}
As the first comment on your question points out you always have to use a loop, but you could monkey patch the Array using prototype like:
Array.prototype.rewriteInto = function(key, rewriteVal){
for(var k in this){
this[k][key] = rewriteVal;
}
};
var testData = new Array();
testData.push({
content: 'something',
date: '15.5.2015',
name: 'Abc',
});
testData.push({
content: 'something',
date: '15.5.2015',
name: 'bla',
});
console.log(testData);
testData.rewriteInto('content', '');
console.log(testData);
So you don't have to rewrite the loop all the time you want to use this functionality.
See example

Property undefined halfway through Javascript array

I'm trying to compare each object in the two arrays in order to find matches. Currently, I am only comparing one property, but plan to compare two properties when I can get this part working.
I find it odd that it works for the first three items in the array and returns an error on the fourth. Here is the console output in Chrome:
Washington
Smith
yes
Jones
Uncaught TypeError: Cannot read property 'name' of undefined
Here is my javascript:
var self = this;
self.people = [
{ id: '1', name: 'Washington' },
{ id: '2', name: 'Smith' },
{ id: '1', name: 'Jones' },
{ id: '1', name: 'Smith' },
{ id: '3', name: 'Washington' }
];
self.params = [
{id: '1', name: 'Jones'},
{id: '2', name: 'Smith'}];
for (var value in self.params) {
for (var value in self.people) {
console.log(self.people[value].name);
if (self.people[value].name == self.params[value].name) {
console.log('yes');
}
}
}
If I remove the if statement, the code runs without error and prints the "names" in the people array twice as expected. Thoughts? Thanks in advance!
You're using twice the variable name "value".
Btw in Javascript the variables aren't scoped at block level (your 2 var declarations in the 2 for), but they're either global or function scoped.
I'm not sure what exactly you want to achieve, but maybe the next lines can give you a hint:
var val,
value;
for (val in self.params) {
for (value in self.people) {
console.log(self.people[value].name);
if (self.people[value].name == self.params[val].name) {
console.log('yes');
}
}
}
for (var value in self.params) {
for (var value1 in self.people) {
console.log(self.people[value1].name);
if (self.people[value1].name == self.params[value].name) {
console.log('yes');
}
}
}
You are using the same variable for both the loops...

Categories

Resources