This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 3 years ago.
I have this JSON:
[[{"product_name":"prod-1","product_url":"http:\\www.google.com"}]]
CODE JS:
var giftLabel = window.checkout.giftLabel; // return json
var array = JSON.parse("[" + giftLabel + "]"); // transform in a array
for(var i = 0; i < array.length; i++) {
for(var j = 0; j < array[i].length; j++) {
var parse = JSON.parse(array[i][j]); //this line not working
console.log(parse.product_name); //this line not working
}
}
I want to extract the values from this JSON and choose an example
OUTPUT:
prod-1
http:\\www.google.com
Can you please tell me where I am wrong and why can't I extract the values from JSON correctly?
var parse = array[i][j];
output = Object.values(parse)
output = ['prod-1', 'http:\www.google.com']
Object.values will return an array of all the values inside the passed object
let d = [
[{
"product_name": "prod-1",
"product_url": "http:\\www.google.com"
}]
]
for (let i = 0; i < d.length; i++) {
for (let j = 0; j < d[i].length; j++) {
if(typeof d[i][j] != "undefined"){
console.log(d[i][j]["product_name"]);
console.log(d[i][j]["product_url"]);
}
}
}
It seem your [[{"product_name":"prod-1","product_url":"http:\\www.google.com"}]] is already in JS object. So you can always access it via
var x = [[{"product_name":"prod-1","product_url":"http:\\www.google.com"}]];
console.log(x[0][0].product_name);
Or if you value is in JSON text, then parse it first:
var x = JSON.parse("you json text");
then continue as above example.
Here's the working in loop:
var x = JSON.parse("json text");
x.forEach(function(i){
i.forEach(function(ii)){
console.log(ii.product_name);
}
});
Related
This question already has answers here:
How can I create a two dimensional array in JavaScript?
(56 answers)
Closed 2 years ago.
So i want to create a chess board by doing a bidemensional array (array in array) but when i try creating it, the array comes out like [0,1] [0,2].... when i would like for it to be [[0,1,2,3...],[0,1,2,3...]...] i dont know if im making myself clear but here is the code, hopefully someone can tell me what am i doing wrong
generarTablero = (tablero) => {
for (var i = 0; i < 8; i++) {
// tablero.push([i])
for (let j = 0; j < 8; j++) {
tablero.push([i, j])
}
}
return tablero
}
generarTablero(tablero);
console.log(tablero)
Just push on each array[i] like this,
generarTablero = (tablero) => {
for (var i = 0; i < 8; i++) {
tablero[i] = [];
for (let j = 0; j < 8; j++) {
tablero[i].push(j)
}
}
return tablero
}
tablero = generarTablero([]);
console.log(tablero)
You're pushing all the elements to a separate array (tablero.push([i, j])).
What you're trying to do, is to create a separate array for each 'row'. Using a tmp array variable, your code could look something like this:
generarTablero = () => {
let arr = [];
for (var i = 0; i < 8; i++) {
let tmp = [];
for (let j = 0; j < 8; j++) {
tmp.push(j);
}
arr.push(tmp);
}
return arr;
}
const tablero = generarTablero();
console.log(tablero)
Of course this could be simplified, using the index instead of a tmp array.
This question already has answers here:
How can I create a two dimensional array in JavaScript?
(56 answers)
Closed 2 years ago.
i know how to create a one dimensional empty array like this:
var data = [];
var length = 100;
console.log(data);
for(var i = 0; i < length; i++) {
data.push(' ');
}
but how do i make the same thing, but two dimensional?
Your data is not an empty array, it is an array of 100 blanks/spaces.
If that's what you mean, then:
var length=100;
var data=[];
for(var i=0; i<length; i++) {
var innerData=[];
for(var j=0; j<length; j++) {
innerData.push(' ');
};
data.push(innerData);
}
I guess what you need is an array of arrays in that case you just fill the outer array with the number of arrays you want, you could use the for loop
var data = [];
var length = 100;
for(var i = 0; i < length; i++) {
data.push([]);
}
console.log(data)
or use fill instead as it's simpler, but the difference is all the arrays created will have same reference as the first array
array=Array(10).fill([])
console.log(array)
This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(141 answers)
Closed 7 years ago.
I have a JavaScript array with objects and an array having some Ids. What I want is to compare the objects in the array with the array of ids and if any id is found in an object, I want to remove that element from the array. Doing this the result shows undefined in place of deleted element.
var data = [{"name": "John_Smith","val":"3","id":"2"},{"name": "Peter_Adams","val":"2","id":"3"},{"name": "Priya_Shetye","val":"1","id":"4"},{"name": "Sara_Brown","val":"4","id":"5"}]
var arr = ["2","5"];
for (var i = 0; i < data.length; i++) {
for(var j=0;j<arr.length;j++){
if (arr[j]==data[i].id ) {
delete data[i];
}
}
}
The result shows [undefined,object object,object object,undefined]. Is there any way to get only [object object,object object]?
use splice instead of delete
loop array from length-1 to 0, otherwise you'll miss deal with some data.
var data = [{"name": "John_Smith","val":"3","id":"2"},{"name": "Peter_Adams","val":"2","id":"3"},{"name": "Priya_Shetye","val":"1","id":"4"},{"name": "Sara_Brown","val":"4","id":"5"}];
var arr = ["2","5"];
for (var i = data.length-1; i >= 0; i--) {
for(var j = 0;j < arr.length;j++){
if (arr[j]==data[i].id ) {
data.splice(i,1);
}
}
}
console.log(data);
charFreq function that's not quite working out. Hit a wall. I know I may need to
do a conditional. Calling the function returns an Object error. I'm attempting
to get string into an empty object displaying the characters like this - Object
{o: 4, p: 5, z: 2, w: 4, y: 1…}. New to Javascript by the way.
Just realized I shouldn't be appending anything. Do I need to do a .push() to
push the array into the object?
function charFreq (string){
var emptyObj = {};
for(var i = 0; i < string.length; i++) {
// console.log(string.charAt(i));
var args = [string.charAt(i)];
var emptyArr = [''].concat(args);
emptyObj += emptyArr
}
return emptyObj
}
undefined
charFreq('alkdjflkajdsf')
"[object Object],a,l,k,d,j,f,l,k,a,j,d,s,f"
You just need to set emptyObj's key of that specific letter to either 1 if it doesn't exist or increment the count if it already does.
function charFreq(string) {
var obj = {};
for (var i = 0; i < string.length; i++) {
if (!obj.hasOwnProperty(string[i])) {
obj[string[i]] = 1;
} else {
obj[string[i]]++;
}
}
return obj;
}
console.log(charFreq('alkdjflkajdsf'));
Try this instead: you need to create an object property first, then increment it. What you do, is implicitly convert the object to a string and concatenate more string data to it (using += and concat).
This is a simple approach:
function charFreq(string){
var emptyObj={};
for(var i=0; i<string.length; i++) {
if(!emptyObj.hasOwnProperty(string[i])){ // if property doesn’t exist
emptyObj[string[i]]=0; // create it and set to 0
}
emptyObj[string[i]]++; // increment it
}
return emptyObj;
}
A modified version of Richard Kho's code:
function charFreq(string) {
var obj = {};
for (var i = 0; i < string.length; i++) {
var c=string[i];
if (c=='') continue;
if (obj[c]==null) obj[c]=0;
obj[c]++;
}
return obj;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Counting occurences of Javascript array elements
I have an array in javascript and for example the array is:
array(1,1,1,1,5,5,7,7);
If can some one please help me to understand how to count similar values,
And how to join similar values,
Thank you all and have a nice day.
var array = [1,1,1,1,5,5,7,7];
var count = 0;
var tempArray = array.sort();
var i;
var prevValue = null;
var joined = [];
for (i = 0; i < array.length; i++) {
if (tempArray[i] != prevValue) {
count++;
prevValue = tempArray[i];
joined.push(prevValue);
}
}
document.write(joined);
If you're looking to uniquely identify array contents:
Array.prototype.unique =
function() {
var a = [];
var l = this.length;
for(var i=0; i<l; i++) {
for(var j=i+1; j<l; j++) {
// If this[i] is found later in the array
if (this[i] === this[j])
j = ++i;
}
a.push(this[i]);
}
return a;
};
var myArray = [1,1,1,1,5,5,7,7];
var uniquedMyArray = myArray.unique();
var valueCountsMyArray = [];
for (var i = 0; i < myArray.length; i++) {
if (valueCountsMyArray[myArray[i]])
valueCountsMyArray[myArray[i]]++;
else
valueCountsMyArray[myArray[i]] = 1;
}
I can suggest using underscore.js. The code you're looking for isn't hard to write, and would be a good learning experience. Once you've done that, underscore is fantastic convenience library that offers what you're looking for, and you don't have to maintain it. :)
The uniq function will give you a copy of your array without duplicates, and the size function will tell you how many values that contains (or just reference the .length property).
Here a solution to count how many time it contains a number.
var count = [];
for(var i=0; i<array.length; i++) {
count[array[i]]++;
}