I want to access salesId of json array but sales is an array also, so do loop twice?
var json = [
{
'id':1,
'sales':
[
{'salesId':123},
{'salesId':456}
]
},
{
'id':2,
'sales':
[
{'salesId':789},
{'salesId':111213}
]
}
];
for (var i in json) {
for (var j in json[i].sales) {
var result = json[i].sales[j].salesId; // here "result" will get salesId
}
}
See by yourself : here
How do you want the output?
json.map(function(x){ return x.sales.map(function(y){return y.salesId})})
returns ids per object
"[[123,456],[789,111213]]"
You can use inner loop instead, incase salesId is dynamic in sales.
for(var i=0;i<json.length;i++){
salesItem = json[i].sales;
for(var j=0;j<salesItem.length;j++){
var item = salesItem[j];
console.log(item.salesId);
}
}
If you don't care about the id you could simply flatten the array like so:
var newArray = json.reduce(function(p,c,i){
return i>1 ? p.concat(c.sales) : p.sales.concat(c.sales);
});
which will give you:
[ // newArray
{'salesId':123},
{'salesId':456},
{'salesId':789},
{'salesId':111213}
]
You could also use reduce to return just an array of salesId too if you wanted.
You don't need to loop twice
//loop through the json array that holds objects
for (var i=0; i<json.length; i++) {
var obj = json[i]; //reference to each object
var sales = obj.sales;
sales.forEach(function(element, index) {
console.log(element.salesId);
});
}
Here are two other ways. Not suggesting these are better, just 'other' ways.
var json = [
{
'id':1,
'sales':
[
{'salesId':123},
{'salesId':456}
]
},
{
'id':2,
'sales':
[
{'salesId':789},
{'salesId':111213}
]
}
];
one way:
var results = [];
for(i=0;i<json.length;i++){
results.push ( JSON.stringify(json[i].sales).match(/(\d+)/g,function($1){
return $1
}))
};
results; // [["123", "456"], ["789", "111213"]]
another way:
var str;
for(i=0;i<json.length;i++){
str = str + JSON.stringify(json[i].sales);
};
str = str.match(/(\d+)/g,function($1){
return $1
})
str; //["123", "456", "789", "111213"]
Related
[NOTE: though similar to this stack question, my question differers significantly (IMO) due to the different structures of the initial variables. Mine is an array, the other questioner's is an object. My array contains nested objects/arrays, the latter of which contain name-value pairs whose values are, unlike the pairs in the other questioner's, not semantically identified.]
I have one big array (arr1) containing 24 objects. Each of the 24 objects contains one object, and one array of six further objects, like so:
var arr1 =
[
{'hour':1,'car':[{'audi':1377},{'bmw':716},{'ford':3819},{'mazda':67},{'toyota':11580},{'tesla':0}]},
{'hour':2,'car':[{'audi':1340},{'bmw':709},{'ford':3420},{'mazda':28},{'toyota':11583},{'tesla':0}]},
...etc, up to hour 24
];
As you can see, each of the 24 objects represents one hour's worth of data on car models and mileage. (What is NOT obvious is that the numeric value in each of the six objects represents miles.)
Now, I want to convert each object in arr1 into one array containing six objects, like below. So Hour 1's data in arr1 would convert to:
var arr2 = [{"car":"audi","miles":1377},{"car":"bmw","miles":716},{"car":"ford","miles":3819},{"car":"mazda","miles":67},{"car":"toyota","miles":11580},{"car":"tesla","miles":0}];
How can I do this? I have tried the following:
var hourx = 1;
var hour = arr1[hourx-1];
var car=hour.car;
for(var hourx1=0;hourx1<car.length;hourx1++){
var xx = car[hourx1];
var newobj = [];
for (var value in xx) {
var chartvar = newobj.push({car:value,miles:xx[value]});
var arr2 = newobj;
}
}
... but if I console.log(arr2); it only gives one array of one object.
I'm stumped. Anybody have an idea how I could accomplish this?
So you want to have an array of arrays as a final result?
var arr1 = [
{'hour':1,'car':[{'audi':1377},{'bmw':716},{'ford':3819},{'mazda':67},{'toyota':11580},{'tesla':0}]},
{'hour':2,'car':[{'audi':1340},{'bmw':709},{'ford':3420},{'mazda':28},{'toyota':11583},{'tesla':0}]}
];
var arr2 = arr1.map(function(hour){
return hour.car.map(function(car){
var carName = Object.keys(car)[0];
return {
"car": carName,
"miles": car[carName]
}
})
})
https://jsfiddle.net/1jjzeeyz/
Try using .map() , Object.keys()
var arr1 = [{
'hour': 1,
'car': [{
'audi': 1377
}, {
'bmw': 716
}, {
'ford': 3819
}, {
'mazda': 67
}, {
'toyota': 11580
}, {
'tesla': 0
}]
}, {
'hour': 2,
'car': [{
'audi': 1340
}, {
'bmw': 709
}, {
'ford': 3420
}, {
'mazda': 28
}, {
'toyota': 11583
}, {
'tesla': 0
}]
}];
var hours = arr1.map(function(cars, index) {
var carNames = Object.keys(cars.car);
var names = carNames.map(function(c) {
var name = Object.keys(cars.car[c])[0];
var res = {};
res["car"] = name;
res["miles"] = cars.car[c][name];
return res
})
return names
})
console.log(hours)
You would have to iterate over the array. Get the first property (let's hope it stays this way). Then get it value. Then create an object and add it to the array. See fiddle here
var arr1 =
[
{'hour':1,'car':[{'audi':1377},{'bmw':716},{'ford':3819},{'mazda':67},{'toyota':11580},{'tesla':0}]},
{'hour':2,'car':[{'audi':1340},{'bmw':709},{'ford':3420},{'mazda':28},{'toyota':11583},{'tesla':0}]},
];
var arr = [];
for (var i = 0; i< arr1[0].car.length; i++){
var car = arr1[0].car[i];
var key = Object.keys(car)[0];
arr.push({
car: key,
miles: car[key]
});
}
a combination of reduce and map will help. /example:
var
arr1 =[
{'hour':1,'car':[{'audi':1377},{'bmw':716},{'ford':3819},{'mazda':67},{'toyota':11580},{'tesla':0}]},
{'hour':2,'car':[{'audi':1340},{'bmw':709},{'ford':3420},{'mazda':28},{'toyota':11583},{'tesla':0}]}
],
arr2 = arr1.reduce(function (collector, item) {
collector.push(item.car.map(function (car/*, idx, list*/) {
var
make = Object.keys(car)[0]
;
return {
"car" : make,
"miles" : car[make]
}
}));
return collector;
}, [])
;
console.log("arr2 : ", arr2);
Here is the JSON example:
jsonData:
{ "Device": { "Content": { "UL": { "index0": "12", "index1": "1", .... "index31": "5", } } } }
This is what I tried, but it didn't work:
var index = [];
var jsonDoc = JSON.parse(data);
for(var i =0; i<32 ; i++)
{
var $arr = "index"+i;
index.push( jsonDoc.Device.Content.UL.$arr);
}
How can I extract the index from 1 to 31 and put it in the index array?
You can access hashes with the [] operator as well:
index.push( jsonDoc.Device.Content.UL[$arr]);
try converting JSON to array .
var o = jsonDoc.Device.Content.UL;
var arr = Object.keys(o).map(function(k) { return o[k] });
refer: Converting JSON Object into Javascript array
You can use for statement to iterate through an object's values:
var index = [];
for(var name in jsonDoc.Device.Content.UL)
{
index.push(jsonDoc.Device.Content.UL[name]));
}
I have an array of objects like this:
[
{ "key": "fruit", "value": "apple" },
{ "key": "color", "value": "red" },
{ "key": "location", "value": "garden" }
]
I need to convert it to the following format:
[
{ "fruit": "apple" },
{ "color": "red" },
{ "location": "garden" }
]
How can this be done using JavaScript?
You can use .map
var data = [
{"key":"fruit","value":"apple"},
{"key":"color","value":"red"},
{"key":"location","value":"garden"}
];
var result = data.map(function (e) {
var element = {};
element[e.key] = e.value;
return element;
});
console.log(result);
also if you use ES2015 you can do it like this
var result = data.map((e) => {
return {[e.key]: e.value};
});
Example
Using an arrow function, with the data called arr
arr.map(e => {
var o = {};
o[e.key] = e.value;
return o;
});
This generates a new Array and does not modify the original
It can be simplified down to one line as
arr.map(e => ({[e.key]: e.value}));
If you can't assume arrow function support yet, you would write this longhand
arr.map(function (e) {
var o = {};
o[e.key] = e.value;
return o;
});
Using map (as suggested in other answers) or the following will do what you want...
var data = [{"key":"fruit","value":"apple"},{"key":"color","value":"red"},{"key":"location","value":"garden"}];
var obj = {};
for(var i = 0; i < data.length; i++) {
obj[data[i]["key"]] = data[i]["value"];
}
In Javascript, obj.property and obj['property'] return same things.
obj['property'] is more flexible because the key 'property' could be a string with some space :
obj['pro per ty'] // work
obj.pro per ty // not work
or
var a = 'property';
obj.a == obj.property // => false
obj[a] == obj.property // => true
So you could try that.
var data = [{"key":"fruit","value":"apple"},{"key":"color","value":"red"},{"key":"location","value":"garden"}]
var new_data = [];
var data_length = data.length; // just a little optimisation for-loop
for (var i = 0; i < data_length; i++) {
var item = data[i]; // to have a vision close of foreach-loop (foreach item of collection)
new_data[i] = {};
new_data[i][item.key] = item.value;
}
console.log(new_data);
// [{"fruit":"apple"},{"color":"red"},{"location":"garden"}]
What you currently have is an array of object, each having two attributes, key and value. If you are not aware of map, you can always run a forEach loop on this array and rearrange the data. Try something like below:
function() {
var newArray = [];
oldArray.forEach(function(x){
var obj= {};
obj[x.key] = x.value;
newArray.push(obj);
});
console.log(newArray);
}
here oldArray is your original data
I'm tryign to write code that will loop through an array "productsArray" and match it against my productPropertyArray to pull matching information.
however productsArray is an array in an array that contains an object with the data. My Question is how can I loop through both arrays and then return the matching data.
Current function:
var pList = productsArray
if (productPropertyArray.length === 0 || productsArray.length === 0) return [];
for (var i = 0; i < pList.length; i++) {
for (var j = 0; j < pList[i].length; j++) {
if (pList[i][j] === productPropertyArray) {
return productPropertyArray;
} else {
continue;
}
}
}
return [];
};
example of pList:
productsArray = [
[{"sku" : "131674"},
{"sku" : "84172"}],
[{"productID" : "1234"}
,{"productID" : "12345"}],
[{"test": 1},{"test": 1}],
[{"test": 1},{"sellAlone": false,"test": 1}],
[{"test": 1}],
[{"sellAlone": false,"test": 1}]
];
example of productPropertyArray: (its an argument thats replaced by the following)
productSKUArray = [
"00544MF24F575",
"131674",
"84172"
];
productPropertyArray is just an argument in the function which is replaced by productSKUArray The setup goes like this: function(productProperty, productPropertyArray, productsArray) {
productProperty is just a string that contains sku or productID
any ideas are appreciated. thanks.
Check this out:
http://jsfiddle.net/v9d7bjms/2/
function find() {
var productsArray = [
[{"sku" : "131674"},
{"sku" : "84172"}],
[{"productID" : "1234"}
,{"productID" : "12345"}],
[{"test": 1},{"test": 1}],
[{"test": 1},{"sellAlone": false,"test": 1}],
[{"test": "00544MF24F575"}],
[{"sellAlone": false,"test": 1}]
],
pList = productsArray,
productSKUArray = [
"00544MF24F575",
"131674",
"84172"
];
// All arrays matching your productsSKUArray
var findings = productsArray.filter(function (productProperty) {
// .some returns true after finding first matching element (and breaks the loop)
return productProperty.some(function (obj) {
var keys = Object.keys(obj);
// We need to get all the "values" from object so we interate over
// the keys and check if any value matches something from productSKUArray
return keys.some(function (key) {
// Check if value exists in productsSKUArray
return productSKUArray.indexOf(obj[key]) > -1;
});
});
});
return findings;
}
console.log(find());
.filter will return all arrays containing objects with values from productSKUArray.
See Array.prototype.filter, Array.prototype.some and Array.prototype.indexOf for method reference.
The inner if needs to refer to pList[i][j].
This will output [{sku: "131674"}, {sku: "84172"}].
var matchingData = [];
for(var productProperties in productsArray){
var pp = productsArray[productProperties];
for(var property in pp) {
var p = pp[property];
for(var propertyName in p){
var propertyValue = p[propertyName];
for(var i in productSKUArray){
if(propertyValue == productSKUArray[i]){
matchingData.push(p);
break;
}
}
}
}
}
but this is just the brute force solution.
How can I convert something like initialArray array of JSON objects into finalObject map?
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
];
var finalObject = {
'id1':'name1',
'id2':'name2',
'id3':'name3',
'id4':'name4'
}
Things to consider:
IDs are strings.
I tried for in loop - couldn't make it to work - http://jsfiddle.net/5af9R/23/
Any ideas?
You need to operate on the objects in your array, not strings containing their indexes in the array.
You should also use a regular for loop to iterate over an array.
Your JSFiddle, fixed:
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var i = 0 ; i < x.length ; i++ ){
var obj = x[i];
resp[obj.id] = obj.img;
}
document.write( JSON.stringify(resp, undefined, 2) );
DEMO
You can loop over the array, and for each object, add a new property to finalObject whose property name is the id, and whose value is the name.
var finalObject = {};
for (var i = 0, max = initialArray.length; i < max; i++)
finalObject[initialArray[i].id] = initialArray[i].name;
resp[key.id] = key.img;
You correctly call it key. But you need a value;
resp[x[key].id] = x[key].img;
var finalObject = initialArray.reduce(function(ret, obj){
ret[obj.id] = obj.name;
return ret;
}, {});
This solution is specific to the property names for the specific question, but Array.prototype.reduce is a function I use all the time for any sort of array iteration that requires a non-array result.
You're not using For In correctly jsFiddle
var x = [ {id:'1', img:'img1'}, {id:'2', img:'img2'}, {id:'3', img:'img3'} ];
var resp = {};
for( var key in x ){
resp['id' + x[key].id] = x[key].img;
}
document.write( JSON.stringify(resp, undefined, 2) );
for (var i=0; i<x.length; i++) {
var id = 'id' + x[i].id;
var img = x[i].img;
resp[id] = img;
}
if i have understood correctly you can do something like
var x =' [ {"id":"1", "img":"img1"}, {"id":"2", "img":"img2"}, {"id":"3", "img":"img3"}]';
var resp = {};
var json = $.parseJSON(x);
$(json).each(function(i,v){
resp[v.id]=v.img;
});
console.log( resp);
DEMO
you talked about json but in the fiddle you provided there was no json even jquery was not added as a resource so i made some assumptions
Today I was on the same question and I didn't find an answer here, except the answer of #adam-rackis.
The way I found is :
var initialArray = [
{ id:'id1', name:'name1' },
{ id:'id2', name:'name2' },
{ id:'id3', name:'name3' },
{ id:'id4', name:'name4' }
],
finalObject = {};
$.each(initialArray, function(k,v) {
finalObject[v.name] = v.value;
});