How to merge JSON objects using plain(without jQuery) JavaScript?
Requirement is to:
Convert from:
chartData=[
{"date":"2014-05-1","CAT1":0.1},
{"date":"2014-05-1","CAT2":0.2},
{"date":"2014-05-1","CAT3":0.3},
{"date":"2014-05-1","UNSET":0.4},
{"date":"2014-05-2","CAT1":0.4},
{"date":"2014-05-2","CAT2":0.3},
{"date":"2014-05-2","CAT3":0.2},
{"date":"2014-05-2","UNSET":0.1}
];
Convert To:
chartData=[
{"date":"2014-05-1","CAT1":0.1,"CAT2":0.2,"CAT3":0.3,"UNSET":0.4},
{"date":"2014-05-2","CAT1":0.4,"CAT2":0.3,"CAT3":0.2,"UNSET":0.1}
]
Here's an example of how to do this... no jquery required.
chartData=[{"date":"2014-05-1","CAT1":0.1},{"date":"2014-05-1","CAT2":0.2},{"date":"2014-05-1","CAT3":0.3},{"date":"2014-05-1","UNSET":0.4},{"date":"2014-05-2","CAT1":0.4},{"date":"2014-05-2","CAT2":0.3},{"date":"2014-05-2","CAT3":0.2},{"date":"2014-05-2","UNSET":0.1}];
function groupProps(orig, key) {
var newArr = [],
groups = {},
newItem, i, j, cur;
for (i = 0, j = orig.length; i < j; i++) {
cur = orig[i];
if (!(cur[key] in groups)) {
groups[cur[key]] = {date: cur[key] };
newArr.push(groups[cur[key]]);
}
for (var prop in cur) {
if (prop != key) {
groups[cur[key]][prop] = cur[prop];
}
}
}
return newArr;
}
console.log(groupProps(chartData, "date"))
Here we iterate backwards through the chartData array operating in place and splicing elements out of the array as the content is merged :
var chartData=[{"date":"2014-05-1","CAT1":0.1},{"date":"2014-05-1","CAT2":0.2},{"date":"2014-05-1","CAT3":0.3},{"date":"2014-05-1","UNSET":0.4}, {"date":"2014-05-2","CAT1":0.4},{"date":"2014-05-2","CAT2":0.3},{"date":"2014-05-2","CAT3":0.2},{"date":"2014-05-2","UNSET":0.1}];
var chartDates = {}; /* stores references to elements for each date */
for (var i=chartData.length-1; i >= 0; i--) {
var date = chartData[i]['date'];
if (date in chartDates) {
for (var k in chartData[i]) {
chartDates[date][k] = chartData[i][k];
}
chartData.splice(i,1);
} else {
chartDates[date] = chartData[i];
}
}
console.log(chartData);
Here is some code that will do it, we first loop through the array to group all of the non-date properties together by date. then append the date property to that intermediate result:
var chartData = [
{"date": "2014-05-1", "CAT1": 0.1},
{"date": "2014-05-1", "CAT2": 0.2},
{"date": "2014-05-1", "CAT3": 0.3},
{"date": "2014-05-1", "UNSET": 0.4},
{"date": "2014-05-2", "CAT1": 0.4},
{"date": "2014-05-2", "CAT2": 0.3},
{"date": "2014-05-2", "CAT3": 0.2},
{"date": "2014-05-2", "UNSET": 0.1}
];
function mergeValues(chartData) {
var tempObj = {};
for (i in chartData) {
var date = chartData[i].date;
//remove the date
delete chartData[i].date;
//get the remaining keys
var keys = Object.keys(chartData[i]);
tempObj[date] = tempObj[date] || {};
for (j in keys) {
tempObj[date][keys[j]] = chartData[i][keys[j]];
}
}
console.log(tempObj);
//{"2014-05-1":{ CAT1:0.1, CAT2:0.2, CAT3:0.3, UNSET:0.4}
//{"2014-05-2":{ CAT1:0.4, CAT2:0.3, CAT3:0.2, UNSET:0.1}
var arr = [];
var keys = Object.keys(tempObj);
for (k in keys) {
var obj = tempObj[keys[k]];
//add the date
obj.date = keys[k];
arr.push(obj);
}
return arr;
}
console.log(mergeValues(chartData));
//
//[
// {"CAT1":0.1,"CAT2":0.2,"CAT3":0.3,"UNSET":0.4,"date":"2014-05-1"},
// {"CAT1":0.4,"CAT2":0.3,"CAT3":0.2,"UNSET":0.1,"date":"2014-05-1"}
//]
Using underscore.js, it can be done pretty easily:
var groupedBy = _.groupBy(chartData, 'date');
var a = _.reduce(groupedBy, function(a, c) {
a.push(_.reduce(c, function(a2, c2){
for(var i in c2) { a2[i] = c2[i]; }
return a2;
}, { }));
return a;
},[]); // 'a' holds the desired merged object
Related
I'm currently working on trying to create a UDF to split a key value pair string based on web traffic into JSON.
I've managed to get as far as outputting a JSON object but I'd like to be able to dynamically add nested items based on the number of products purchased or viewed based on the index number of the key.
When a product is only viewed, there is always only one product in the string. Only when its a transaction is it more than one but I think it would be good to conform the structure of the json and then identify a purchase or view based on the presence of a transactionid. For example:
Item Purchased:
sessionid=12345&transactionid=555555&product1=apples&productprice1=12&product1qty=1&product2=pears&productprice2=23&product2qty=3&transactionamount=58
The output should look something like this:
[
{
"sessionid":12345,
"transactionid":555555,
"transactionamount":58
},
[
{
"productline":1,
"product":"apples",
"productprice":12,
"productqty":1
},
{
"productline":2,
"product":"pears",
"productprice":23,
"productqty":2
}
]
]
Item Viewed:
sessionid=12345&product1=apples&productprice1=12&product1qty=1&product2=pears&productprice2=23&product2qty=3
[
{
"sessionid":12345,
"transactionid":0,
"transactionamount":0
},
[
{
"productline":1,
"product":"apples",
"productprice":12,
"productqty":1
}
]
]
The result I'll be able to parse from JSON into a conformed table in a SQL table.
What I've tried so far is only parsing the string, but its not ideal to create a table in SQL because the number of purchases can vary:
var string = "sessionid=12345&transactionid=555555&product1=apples&productprice1=12&product1qty=1&product2=pears&productprice2=23&product2qty=3&transactionamount=58";
function splitstring(queryString) {
var dictionary = {};
if (queryString.indexOf('?') === 0) {
queryString = queryString.substr(1);
}
var parts = queryString.split('&');
for (var i = 0; i < parts.length; i++) {
var p = parts[i];
// Step 2: Split Key/Value pair
var keyValuePair = p.split('=');
var key = keyValuePair[0];
var value = keyValuePair[1];
dec_val = decodeURIComponent(value);
final_value = dec_val.replace(/\+/g, ' ');
dictionary[key] = final_value;
}
return (dictionary);
}
console.log(splitstring(string));
Thanks in advance!!!
Feel like this would be less clunky with better param naming conventions, but here's my take...
function parseString(string) {
var string = string || '',
params, param, output, i, l, n, v, k, pk;
params = string.split('&');
output = [{},
[]
];
for (i = 0, l = params.length; i < l; i++) {
param = params[i].split('=');
n = param[0].match(/^product.*?([0-9]+).*/);
v = decodeURIComponent(param[1] || '');
if (n && n[1]) {
k = n[1];
output[1][k] = output[1][k] || {};
output[1][k]['productline'] = k;
pk = n[0].replace(/[0-9]+/, '');
output[1][k][pk] = v;
} else {
output[0][param[0]] = v;
}
}
output[1] = output[1].filter(Boolean);
return output;
}
var string = "sessionid=12345&transactionid=555555&product1=apples&productprice1=12&product1qty=1&product2=pears&productprice2=23&product2qty=3&transactionamount=58";
console.log(parseString(string));
output:
[
{
"sessionid": "12345",
"transactionid": "555555",
"transactionamount": "58"
},
[{
"productline": "1",
"product": "1",
"productprice": "12"
}, {
"productline": "2",
"product": "3",
"productprice": "23"
}]
]
There's probably a far nicer way to do this, but I just wrote code as I thought about it
var string = "sessionid=12345&transactionid=555555&product1=apples&productprice1=12&product1qty=1&product2=pears&productprice2=23&product2qty=3&transactionamount=58";
function splitstring(queryString) {
var dictionary = {};
if (queryString.indexOf('?') === 0) {
queryString = queryString.substr(1);
}
var parts = queryString.split('&');
for (var i = 0; i < parts.length; i++) {
var p = parts[i];
// Step 2: Split Key/Value pair
var keyValuePair = p.split('=');
var key = keyValuePair[0];
var value = keyValuePair[1];
dec_val = decodeURIComponent(value);
final_value = dec_val.replace(/\+/g, ' ');
dictionary[key] = final_value;
}
return (dictionary);
}
function process(obj) {
let i = 1;
const products = [];
while(obj.hasOwnProperty(`product${i}`)) {
products.push({
[`product`]: obj[`product${i}`],
[`productprice`]: obj[`productprice${i}`],
[`productqty`]: obj[`product${i}qty`]
});
delete obj[`product${i}`];
delete obj[`productprice${i}`];
delete obj[`product${i}qty`];
++i;
}
return [obj, products];
}
console.log(process(splitstring(string)));
By the way, if this is in the browser, then splitstring can be "replaced" by
const splitstring = string => Object.fromEntries(new URLSearchParams(string).entries());
var string = "sessionid=12345&transactionid=555555&product1=apples&productprice1=12&product1qty=1&product2=pears&productprice2=23&product2qty=3&transactionamount=58";
function process(string) {
const splitstring = queryString => {
var dictionary = {};
if (queryString.indexOf('?') === 0) {
queryString = queryString.substr(1);
}
var parts = queryString.split('&');
for (var i = 0; i < parts.length; i++) {
var p = parts[i];
// Step 2: Split Key/Value pair
var keyValuePair = p.split('=');
var key = keyValuePair[0];
var value = keyValuePair[1];
dec_val = decodeURIComponent(value);
final_value = dec_val.replace(/\+/g, ' ');
dictionary[key] = final_value;
}
return (dictionary);
};
let i = 1;
const obj = splitstring(string);
const products = [];
while (obj.hasOwnProperty(`product${i}`)) {
products.push({
[`product`]: obj[`product${i}`],
[`productprice`]: obj[`productprice${i}`],
[`productqty`]: obj[`product${i}qty`]
});
delete obj[`product${i}`];
delete obj[`productprice${i}`];
delete obj[`product${i}qty`];
++i;
}
return [obj, products];
}
console.log(process(string));
I have two json:
I want to create json with those two array;
var __columns = ["Field1", "Field2", "Field3", "Field4"];
var __rows = ["valueField1_1", "valueField2_1", "valueField3_1", "valueField4_1", "valueField1_2", "valueField2_2", "valueField3_2", "valueField4_2", "valueField1_3", "valueField2_3", "valueField3_3", "valueField4_3"];
The thing is that I wanna create something like this
var json = [{
"Field1":"valueField1_1",
"Field2":"valueField2_1",
"Field3":"valueField3_1",
"Field4":"valueField4_1"
},{
"Field1":"valueField1_2",
"Field2":"valueField2_2",
"Field3":"valueField3_2",
"Field4":"valueField4_2"
},{
"Field1":"valueField1_3",
"Field2":"valueField2_3",
"Field3":"valueField3_3",
"Field4":"valueField4_3"
}]
ES6 solution using Array.from and Array#reduce methods.
var __columns = ["Field1", "Field2", "Field3", "Field4"];
var __rows = ["valueField1_1", "valueField2_1", "valueField3_1", "valueField4_1", "valueField1_2", "valueField2_2", "valueField3_2", "valueField4_2", "valueField1_3", "valueField2_3", "valueField3_3", "valueField4_3"];
var res = Array.from({
// generate array with particular size
length: __rows.length / __columns.length
// use map function to generate array element
}, (_, i) => __columns.reduce((obj, e, i1) => {
// define object property based on the index values
obj[e] = __rows[i * __columns.length + i1];
return obj;
// set empty object as initial argument
}, {}));
console.log(res);
function convertToJsonArr(__columns, __rows){
var obj = {};
var arr = [];
var len = __columns.length;
var count = 0;
$.each(__rows , function(key, value){
if(count >= len){
count = 0;
arr.push(obj);
obj = {};
}
obj[__columns[count++]] = value;
})
arr.push(obj);
return arr;
}
you can call like convertToJsonArr(__columns, __rows);
One way to achieve this is using loops
var __columns = ["Field1", "Field2", "Field3", "Field4"];
var __rows = ["valueField1_1", "valueField2_1", "valueField3_1", "valueField4_1", "valueField1_2", "valueField2_2", "valueField3_2", "valueField4_2", "valueField1_3", "valueField2_3", "valueField3_3", "valueField4_3"];
var arr = [];
for(var i = 0; i < __rows.length; i = i + __columns.length){
var tempObj = {};
for(var j = 0; j < __columns.length; ++j){
tempObj[__columns[j]] = __rows[i];
}
arr.push(tempObj);
}
console.log(arr);
I have an array of object, I want to know the best way of concatenating values from similar properties e.g.
arr:[
{obj:{obj_type:1, obj_foo:"joe"}},
{obj:{obj_type:2, obj_foo:"developer"}},
{obj:{obj_type:1, obj_foo:"kevin"}},
{obj:{obj_type:2, obj_foo:"architect"}}
]
I need to concatenate properties value of same obj_type property.
expected result should be:
arr:[
{obj:{obj_type:1, obj_foo:"joe|kevin"}},
{obj:{obj_type:2, obj_foo:"developer|architect"}}
]
i.e. values are concatenated based on obj_type.
I think code like this might be helpful for you:
//Objects to work with:
var arr = [{obj:{obj_type:1, obj_foo:"joe"}},
{obj:{obj_type:2, obj_foo:"developer"}},
{obj:{obj_type:1, obj_foo:"kevin"}},
{obj:{obj_type:2, obj_foo:"architect"}}];
//Map from obj_type to {obj: …} objects:
var map = {};
//Iterating arr:
for(var i = 0; i < arr.length; i++){
var o = arr[i], type = o.obj.obj_type;
if(type in map){
map[type].obj.obj_foo += '|' + o.obj.obj_foo;
}else{
map[type] = o;
}
}
//Putting map values to arr:
arr = [];
for(var key in map){
arr.push(map[key]);
}
//Done:
console.log(arr);
Produced output looks like this:
[ { obj: { obj_type: 1, obj_foo: 'joe|kevin' } },
{ obj: { obj_type: 2, obj_foo: 'developer|architect' } } ]
This variant doesn't change content of initial array.
var types = {};
var newArr = [];
var type, newObj;
for ( var i = 0; i < arr.length; ++i ) {
type = arr [ i ].obj.obj_type;
if ( type in types ) {
types[ type ].obj.obj_foo += '|' + arr[ i ].obj.obj_foo;
} else {
newObj = {
obj: {
obj_type: arr[ i ].obj.obj_type,
obj_foo: arr[ i ].obj.obj_foo
}
};
types[ type ] = newObj;
newArr.push( newObj );
}
}
return newArr; // result array
This might be the simplest approach:
// Your array
var arr = [
{obj:{obj_type:1, obj_foo:"joe"}},
{obj:{obj_type:2, obj_foo:"developer"}},
{obj:{obj_type:1, obj_foo:"kevin"}},
{obj:{obj_type:2, obj_foo:"architect"}}
];
// Loop over all elements
for(var i = 0; i < arr.length; i++) {
var a = arr[i].obj;
// Compare to each other element
for(var j = i + 1; j < arr.length; j++) {
var b = arr[j].obj;
// If the obj_type is equal...
if(a.obj_type === b.obj_type) {
// Merge data...
a.obj_foo += '|' + b.obj_foo;
// Remove other element
arr.splice(j--, 1);
}
}
}
Output (from node.js):
[ { obj: { obj_type: 1, obj_foo: 'joe|kevin' } },
{ obj: { obj_type: 2, obj_foo: 'developer|architect' } } ]
I have an array of arrays which looks like this:
arr = [
["Bob","USA","55"],
["Frank","Canada","20"],
["Bob","UK","35"],
["Bob","France","38"],
["Anna","Poland","22"]
]
I like to remove duplicate arrays which have the same value on the first position(the same name) - so I'd like to my output will look like that:
arr = [
["Bob","USA","55"],
["Frank","Canada","20"],
["Anna","Poland","22"]
]
I'm trying to do this in this way:
uniqueArr = []
for (var i in arr) {
if (uniqueArr.indexOf(arr[i][0]) === -1)) {
uniqueArr.push(arr[i][0])
}
Everything works ok - my output looks like Bob, Frank, Anna
But the problem is when I'm trying to recive whole arrays with unique value name. When I'm doing:
uniqueArr = []
for (var i in arr) {
if (uniqueArr.indexOf(arr[i][0]) === -1)) {
uniqueArr.push(arr[i])
}
My output looks exactly like the input array. Do you know where I'm doing wrong?
You could keep track of the key string in a separate array and track that instead, for example:
var uniqueArr = [],
keys = []; // Create an array for storing the key values
for (var i in arr) {
if (keys.indexOf(arr[i][0]) === -1) {
uniqueArr.push(arr[i]); // Push the value onto the unique array
keys.push(arr[i][0]); // Push the key onto the 'key' array
}
}
console.log(uniqueArr);
jsFiddle example
try
arr = [
["Bob", "USA", "55"],
["Frank", "Canada", "20"],
["Bob", "UK", "35"],
["Bob", "France", "38"],
["Anna", "Poland", "22"]
]
var newArr = [];
for (var i = 0; i < arr.length; i++) {
if (isInArr(newArr, arr[i]) == -1) {
newArr.push(arr[i]);
}
}
function isInArr(checkArr, value) {
var index = -1;
for (var i = 0; i < checkArr.length; i++) {
if (checkArr[i][0] == value[0]) {
index = i;
break;
}
}
return index;
}
console.log(newArr)
DEMO
Take a look atthe function unique2. It works!
originalArr = [
["Bob", "USA", "55"],
["Frank", "Canada", "20"],
["Bob", "UK", "35"],
["Bob", "France", "38"],
["Anna", "Poland", "22"]
];
function unique(arr) {
uniqueArr = [];
for (var i in arr) {
if (uniqueArr.indexOf(arr[i][0]) === -1) {
uniqueArr.push(arr[i]);
}
}
return uniqueArr;
}
function unique2(arr) {
uniqueArr = [];
keys = [];
for (var i in arr) {
if (keys.indexOf(arr[i][0]) === -1) {
uniqueArr.push(arr[i]);
keys.push(arr[i][0]);
}
}
return uniqueArr;
}
var response = document.getElementById('response');
response.textContent = JSON.stringify(unique(originalArr));
var response2 = document.getElementById('response2');
response2.textContent = JSON.stringify(unique2(originalArr));
<h1>Your code</h1>
<div id="response"></div>
<h1>My code</h1>
<div id="response2"></div>
I am new to JavaScript and wondering how can I compare an array with another array consists of JavaScript objects.
The array is a series of sorted time in the "YYYY-MM-DD" format.
The array of objects missed some price values of several days.
I want to find the missed value and assign it as "NULL".
For example, I have an array as:
array = ['2014-10-09','2014-10-10','2014-10-11','2014-10-12'];
and an array with objects as:
objArray = [{
date:"2014-10-09",
price:"100"
},
{
date:"2014-10-10",
price:"99"
},
{
date:"2014-10-12",
price:"102"
}];
I want to get the price array in this way:
priceResult = [100, 99, "NULL", 102];
What would be the most efficient way without using other libraries? I wanted to see if anyone had a more elegant solution. I deeply appreciate your help.
You can create a lookup set from the object array, then you can use that to translate the dates to prices.
This scales well, as it is an O(n+m) solution rather than the O(n*m) solution that you get if you use a loop in a loop to find the prices.
var array = ['2014-10-09','2014-10-10','2014-10-11','2014-10-12'];
var objArray = [{ date:"2014-10-09", model:"A", price:"100" },{ date:"2014-10-10", model:"A", price:"99" },{ date:"2014-10-12", model:"A", price:"102" }];
var lookup = {};
for (var i = 0; i < objArray.length; i++) {
lookup[objArray[i].date] = parseInt(objArray[i].price, 10);
}
var priceResult = [];
for (var i = 0; i < array.length; i++) {
if (lookup.hasOwnProperty(array[i])) {
priceResult.push(lookup[array[i]]);
} else {
priceResult.push('NULL');
}
}
// output result in StackOverflow snippet
document.write(JSON.stringify(priceResult));
Note: Instead of the string 'NULL' you might want to use the value null instead, as it is generally easier to handle.
lodash is the best library for this. But you did say "without using other libraries", so you will need to do it natively.
The easiest way to do it is nested for loops:
var i, j, d, res = [];
for (i=0; i<dateArray.length; i++) {
d = dateArray[i];
for (j=0; j<objArray.length; j++) {
if (objArray[j] && objArray[j].date && objArray[j].date === d) {
res.push(objArray[j].price);
j = objArray.length; // don't waste energy searching any more, since we found it
}
}
}
// res now contains all you wanted
If objArray is really big, and you don't want to search it multiple times, then you could turn it into an object indexed by date:
var i, obj = {}, d, res = [];
for (i=0; i<objArray.length; i++) {
if (objArray[i] && objArray[i].date) {
obj[objArray[i].date] = objArray[i];
}
}
for (i=0; i<dateArray.length; i++) {
d = dateArray[i];
res.push(obj[d] ? obj[d].price : null : null);
}
// res now contains all you wanted
Loop trough the object and search for the date in your array
// Add contains to array proto: http://css-tricks.com/snippets/javascript/javascript-array-contains/
var priceResult = [];
for(var i in objArray) {
if(dateArray.contains(objArray[i].date)) priceResult.push(objArray[i].date));
}
console.log('matches:', priceResult);
This function will give you map of all individual arrays in your object array
function getArrayMap(array) {
var map={}
for(var i=0;i<array.length;i++){
var o = array[i];
for(var k in o){
if(!map[k]){
map[k]=[];
}
map[k].push(o[k]);
}
}
return map;
}
you can use it like -
var map = getArrayMap(objArray);
console.log(map["date"]);//date array
console.log(map["price"]);//price array
console.log(map["model"]);//model array
If i am understanding your question correctly, for all the values in array, you want to check the objArr and find the price for each date, and if not found u want to inset null. If this is what you want, then following will help
var found= false;
var list=[];
for(var i=0; i< dateArray.length; i++)
{
for(var j=0; j< objArray.length; j++)
{
if(objArray[j].date == dateArray[i])
{
list.push(objArray[j].price);
found = true;
}
}
if(!found)
{
list.push("null");
}
found = false;
}
alert(list);
(I'm going to call your first array dates rather than array, to avoid confusion.)
There are basically two options:
Loop through your dates array and, for each entry, loop through the objArray looking for a match, and when found add to your priceResult array, or
Build a map from your objArray, then loop through yourdatesarray once, building thepriceResult` array.
Looping and Looping
You can loop through your dates array using forEach, and you can use Array#some to find out whether your objArray contains the date and add to priceResult if so (it's an ES5 feature, but you can polyfill it for really old browsers):
var priceResult = [];
dates.forEach(function(date) {
objArray.some(function(object) {
if (object.date == date) {
priceResult.push(object.price);
return true;
}
});
});
Array#some keeps looping until you return true, which is why we do that when we find the firs tmatch. That's why I say this is "looping and looping," even though we only write one loop, the other is within Array#some.
var dates = ['2014-10-09', '2014-10-10', '2014-10-11', '2014-10-12'];
var objArray = [
{
date: "2014-10-09",
model: "A",
price: "100"
},
{
date: "2014-10-10",
model: "A",
price: "99"
},
{
date: "2014-10-12",
model: "A",
price: "102"
}
];
// Do it
var priceResult = [];
dates.forEach(function(date) {
objArray.some(function(object) {
if (object.date == date) {
priceResult.push(object.price);
return true;
}
});
});
snippet.log(priceResult.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Mapping and Looping
First, create a map of prices by date:
var prices = {};
objArray.forEach(function(object) {
prices[object.date] = object.price;
});
...then create your results:
var priceResult = [];
dates.forEach(function(date) {
if (prices.hasOwnProperty(date)) {
priceResult.push(prices[date]);
}
});
var dates = ['2014-10-09', '2014-10-10', '2014-10-11', '2014-10-12'];
var objArray = [
{
date: "2014-10-09",
model: "A",
price: "100"
},
{
date: "2014-10-10",
model: "A",
price: "99"
},
{
date: "2014-10-12",
model: "A",
price: "102"
}
];
// Create the map
var prices = {};
objArray.forEach(function(object) {
prices[object.date] = object.price;
});
// Create your results:
var priceResult = [];
dates.forEach(function(date) {
if (prices.hasOwnProperty(date)) {
priceResult.push(prices[date]);
}
});
// Show them
snippet.log(priceResult.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
var dates = ['2014-10-09','2014-10-10','2014-10-11','2014-10-12'];
var objArray = [{date:"2014-10-09", model:"A", price:"100" }, {date:"2014-10-10", model:"A", price:"99" }, {date:"2014-10-12", model:"A", price:"102" }];
var val;
var priceResult = [];
for (var a in dates) {
val = null;
for (var b in objArray) {
if (dates[a] == objArray[b].date) {
val = objArray[b].price;
}
}
priceResult.push(val);
}
var dates = ['2014-10-09', '2014-10-10', '2014-10-11', '2014-10-12'];
var objArray = [{
date: "2014-10-09",
model: "A",
price: "100"
}, {
date: "2014-10-10",
model: "A",
price: "99"
}, {
date: "2014-10-12",
model: "A",
price: "102"
}];
var val;
var priceResult = [];
for (var a in dates) {
val = null;
for (var b in objArray) {
if (dates[a] == objArray[b].date) {
val = objArray[b].price;
}
}
priceResult.push(val);
}
// output result in StackOverflow snippet
document.write(JSON.stringify(priceResult));
Try this:
var temp[]
temp= jQuery.grep(objArray , function (n, i)
{
for(j=0;j<dateArray.lenght+j++ )
if( n.date === dateArray[j])
return n.price;
);
dateArray = ["2014-10-09", "2014-10-10", "2014-10-11", "2014-10-12"];
function ObjectExample(date1,model,price)
{
this.date1 = date1;
this.model = model;
this.price = price;
}
var objArray = [new ObjectExample("2014-10-09","A","100"), new ObjectExample("2014-10-10","A","99"), new ObjectExample("2014-10-12","A","102")];
var i = 0;
var priceDate = new Array();
var count = 0;
while(i < dateArray.length)
{
var j = 0;
while(j < objArray.length)
{
if(dateArray[i] == objArray[j].date1)
{
priceDate[count] = objArray[j].price;
break;
}
else priceDate[count] = "NULL";
j = j + 1;
}
i = i + 1;
count++;
}
document.write(priceDate);