jQuery Loop though an object of arrays - javascript

I have a simple object with some simple arrays. I want to loop through each item in the object and check part of the array. For example, if a '0' or a '1' then do something.
var formvalidation = {
title: ['id1', 0],
categories: ['id2', 1],
price: ['id3', 1],
video: ['id4', 0],
fileTypes: ['id5', 0]
}
I've tried the following but I get the entire object in each loop.
jQuery(formvalidation).each(function(){
//Gives the entire object.
console.log();
});

It's a bit unclear what kind of processing you're trying to do with each property (see my comment requesting clarification).
The example below demonstrates how to loop through each property and extract the first and second value from the arrays you're storing. This example is meant to illustrate how to access each property and its values only - you'll obviously need to plug your logic in where appropriate.
var formvalidation = {
title: ['id1', 0],
categories: ['id2', 1],
price: ['id3', 1],
video: ['id4', 0],
fileTypes: ['id5', 0]
};
for (let prop in formvalidation) {
if (Object.prototype.hasOwnProperty.call(formvalidation, prop)) {
console.log(`Value of prop, ${prop}, is ${formvalidation[prop] [0]}:${formvalidation[prop][1]}`);
}
}
You could also use Object.keys, which is a bit cleaner:
var formvalidation = {
title: ['id1', 0],
categories: ['id2', 1],
price: ['id3', 1],
video: ['id4', 0],
fileTypes: ['id5', 0]
};
const keys = Object.keys(formvalidation)
for (const key of keys) {
console.log(formvalidation[key]);
}

Not to say that the previous answer here isn't right, but I thought Id go with what it led me to as the answer in this case.
jQuery.each(formvalidation, function(key, value){
if (value[1] == 0) {
e.preventDefault();
}
})

Related

Mapping an Array Based on Another Array

I'm working on a project where I need to change the values of one array should the first index of one of its nested arrays be found within the second array. For example:
Array One
[12345, [67890, 1], [09876, 2]]
Array Two
[
[
180547,
'180547 text',
'more text',
...etc
], [
67890,
'67890 text',
'more text',
...etc
],
...etc
]
I need to iterate through each of the nested arrays in Array One and check if the first value in each nested array is present in the any of the arrays in Array Two. From there, I need to copy Array Two's array, and replace the first value of the nested array in Array One.
I know that was probably a little confusing, so here's an example output of the above arrays:
Output
[12345, [[67890, '67890 text', 'more text', ...etc], 1], [09876, 2]]
ES6+ is preferred, but not necessary.
EDIT:
As asked for, so given -
Function jargon aside, here's the best I was able to come up with on my own:
gid.steal()
.then(dataset => {
let o = dataset.forEach(group => {
group.map((person, i) => {
i === 0 ? person : rows.forEach(row => {
row[0] === person[0] && row[row.length - 1] === '-3' ? [row, person[1]] : null
})
})
})
console.log(o)
})
.catch(err => rej(err))
//dataset would be Array One and rows would be Array Two
This returns undefined
I have a feeling I'm either trying to get too complicated/clever with it, or I'm totally out of bounds on this method.
Figured it out. It turns out I was definitely trying to be more complicated than I needed to be. I just needed some simple maps and a filter.
let arr1 = [
['john', 1, 2, 3, 4, '5'],
['jane', 1, 2, 3, 4, '5'],
['jane', 1, 2, 3, 4, '-3'],
['joe', 1, 2, 3, 4, '-3']
]
let arr2 = [
['number', ['jane', 1]]
]
const fx = data => {
return data.map(s => {
return s.map((t, u) => {
return u === 0
? t
: [arr1.filter(v => v[0] === t[0] && v.indexOf('-3') >= 0)[0], t[1]]
})
})
}
console.log(fx(arr2))

Javascript modifies the orignal object on using map on a nested array

Consider the following example. An array is contained inside an object and I am using map to modify the contents of the array.
let temp = {
name:'Scott',
arr: [1, 2, 3, 4],
};
console.log(temp);
let promise = temp.arr.map((obj) => {
return obj*5;
});
Promise.all(promise).then( (temp) => {
console.log(temp);
});
Output is :
{ name:'Scott' ,arr: [ 1, 2, 3, 4 ] }
[ 5, 10, 15, 20 ]
Can someone please explain me why is the original object modified ?
The original was never updated, but you changed what temp refers to.
Try this instead:
Promise.all(promise).then( (result) => {
console.log("temp", temp);
console.log("result", result);
});

Add Key To Javascript Array

I'm looking to append keys to the array which I have created, so I have an array of numbers:
var Array1 = [1, 2, 3, 4, 5];
I want to convert the array so it looks like this:
Array1 = [{ x: 1 }, { x: 2 }, { x: 3 }, { x: 4 }, { x: 5 }];
How do I append to each value in the array like so?
https://www.sitepoint.com/a-beginners-guide-to-data-binding-in-d3-js/ - Within this article, we can see they have an array called 'Data' - An array of objects. Now I have a simple array full of numbers and I need it to be converted as described above
You could use Array#map together with short hand properties for a new object for each element of the array.
var array = [1, 2, 3, 4, 5],
objects = array.map(x => ({ x }));
console.log(objects);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Array1 = Array1.map(entry => ({x: entry}));

How do I use reduce() to mimic the capabilities of forEach()?

I'm trying to accomplish a task with reduce() that I know how to do with forEach(). Unfortunately I'm not sure how to structure the syntax and I can't find a good example.
Example 1) In this code I use forEach() to insert the word species into the first index of each array.
"use strict";
var creatureArray;
creatureArray = [
['zombie', 30, 1, 'bite', 0, 5],
['skeleton', 10, 2, 'sword', 1, 10],
['orc', 15, 4, 'club', 1, 7]
];
creatureArray.forEach(function(value, index, array) {
array[index].unshift('species');
});
console.log(creatureArray);
Example 2) In this code I try to accomplish something similar using .reduce(). However I know that I'm missing a piece of syntax. I can't figure out how to apply the updated array to the accumulator which is then returned as an object. Thanks so much for any help!
"use strict";
var creatureArray, creatureObject;
creatureArray = [
['zombie', 30, 1, 'bite', 0, 5],
['skeleton', 10, 2, 'sword', 1, 10],
['orc', 15, 4, 'club', 1, 7]
];
creatureObject = creatureArray.reduce(function(accumulator, currentValue, index, array) {
array[index].unshift('species');
//what goes here?
return accumulator;
}, {});
console.log(creatureObject);
Here is how you can do accomplish it.
"use strict";
var creatureArray, creatureObject;
creatureArray = [
['zombie', 30, 1, 'bite', 0, 5],
['skeleton', 10, 2, 'sword', 1, 10],
['orc', 15, 4, 'club', 1, 7]
];
creatureObject = creatureArray.reduce((accumulator, currentValue) => {
return [...accumulator, ['species', ...currentValue]];
}, []);
console.log(creatureObject);
The ... syntax above is called the Spread Operator.
When applied it expands the elements of the array into the new array created by the enclosing [ and ], placing each element from the old array as a top level element into the new array. This results in a flat array instead of a nested array. E.g [[1, 2]] -> [[1, 2]], but [...[1, 2]] -> [1, 2].
This is highly useful because it enables both simple concatenation as well as insertion of top level elements either before or after the expanded array.
Consider:
"use strict";
const names = ['Linus', 'Jane', 'David'];
const withJakeAppended = [...names, 'Jake'];
const withJakePrepended = ['Jake', ...names];
[names, withJakeAppended, withJakePrepended].forEach(xs => console.log(xs));
As you can see, when we spread an Array it is not modified, so the pleasant syntax also enables improved ergonomics for immutable, value oriented programming.
Even better, ... works with Sets and Maps as well. In fact, it works any Iterable object, including ones we can create ourselves.
I might add that using the fourth argument to either Array.prototype.forEach or Array.prototype.forEach is a poor practice that should be avoided.
Note if you need to do this in a browser without ES2015 support, you can write
"use strict";
var creatureArray, creatureObject;
creatureArray = [
['zombie', 30, 1, 'bite', 0, 5],
['skeleton', 10, 2, 'sword', 1, 10],
['orc', 15, 4, 'club', 1, 7]
];
creatureObject = creatureArray.reduce(function (accumulator, currentValue) {
return accumulator.concat([['species'].concat(currentValue)]);
}, []);
console.log(creatureObject);
map is more apropriate in this case:
var creatureArray = [ ['zombie' , 30, 1, 'bite' , 0, 5],
['skeleton', 10, 2, 'sword', 1, 10],
['orc' , 15, 4, 'club' , 1, 7] ]
var creatureObject = creatureArray.map(currentValue => ['species', ...currentValue] )
console.log( JSON.stringify( creatureObject ).replace(/],/g, '],\n ') )

Why are the returned data the same?

let statList = {
title: {
x: "center"
},
xAxis: {
type: "category",
axisTick: {
alignWithLabel: true
}
},
yAxis: {
type: "value"
}
};
let statObj = {};
statObj.chatObj = Object.create(statList);
statObj.carObj = Object.create(statList);
statObj.saObj = Object.create(statList);
statObj.chatObj.xAxis.data = [1, 2, 3];
statObj.carObj.xAxis.data = [4, 5, 6];
statObj.saObj.xAxis.data = [7, 8, 9];
console.log(statObj)
Why are the returned statObj.XX.xAxis.data the same?
Why when I use console.log(JSON.stringify(statObj)), the result is {"chatObj":{},"carObj":{},"saObj":{}} ?
While setting statObj.chatObj.xAxis, xAxis is not found on chatObj, so xAxis is searched on the prototype chain (statList is the prototype of chatObj), where we could find it there. Until now we are done with the part statObj.chatObj.xAxis, next we move to create a .data key which will be create on statList.xAxis. Assignments with both statObj.carObj.xAxis.data and statObj.saObj.xAxis.data oberride what was set by statObj.chatObj.xAxis.data on statList.xAxis.data, that is why we have the result of statObj.XX.xAxis.data the last set value which is [7, 8, 9].
Usually I do solve this by using the following trick
statObj.chatObj = JSON.parse(JSON.stringify(statList));
I do not say this is a good practice, but in this way I am making sure the created object has it's own adress in the memory.
The problem with Object.assign() is that it is not working with nested properties, anyway the created object's are mutable.

Categories

Resources