Trying to split a javascript object in to a hash array.. I have to split the contents inside the array based on the occurrence of symbol"|"
my input array looks like
{
"testFieldNames": ["testNumber", "testName", "testDate1", "testDate2"]
},
"data": [
"4|Sam|2012-02-10T00:00Z",
"0|Wallace|1970-01-01T00:00Z|2012-02-10T00:00Z"
]
};
and the expected output is [{"testNumber" : "4", "testName" : "Sam", "testDate1" : "2012-02-10T00:00Z", "testDate2" : "0"},{"testNumber" : "0", "testName" : "Wallace", "testDate1" : "1970-01-01T00:00Z", "testDate2" : "2012-02-10T00:00Z"}]
This is what I've tried.. but it is not complete.
http://jsfiddle.net/Dwfg6/1/
var header = responseData.header.testFieldNames,
length = header.length,
result;
result = responseData.data.map(function(el) {
var ret = {}, data = el.split('|'), i;
for (i=0; i < length; i++) {
ret[header[i]] = data[i];
}
return ret;
});
console.log(result);
The demo. (Note: you may use jQuery.map methods instead for old browsers.)
You were close...
http://jsfiddle.net/Dwfg6/4/
var responseData = {
"header": {
"testFieldNames": ["testNumber", "testName", "testDate1", "testDate2"]
},
"data": [
"4|Sam|2012-02-10T00:00Z|2012-02-10T00:00Z",
"0|Wallace|1970-01-01T00:00Z|2012-02-10T00:00Z"
]
};
function buildData(fields, data) {
var output = [];
if (fields && fields.length && data && data.length) {
for (var i = 0; i < data.length; i++) {
var row = data[i].split("|");
output[i] = {};
while (row.length) {
output[i][fields[4 - row.length]] = row.shift();
}
}
}
return output;
}
console.log(buildData(responseData.header.testFieldNames, responseData.data));
fiddle : http://jsfiddle.net/FjJse/1/
My answer:
fiddle
function mapData (data) {
'use strict';
var result=[];
var i, j;
var values = [];
var resultObj;
for(i=0; i < data.testFieldValues.length; i += 1) {
values = data.testFieldValues[i].split("|");
resultObj = {};
for(j = 0; j < data.testFieldNames.length; j += 1) {
resultObj[data.testFieldNames[j]] = values[j];
}
result.push(resultObj);
}
return result;
}
//$(document).ready(function() {
// 'use strict';
var data = {testFieldNames: ["testNumber", "testName", "testDate1", "testDate2"],
testFieldValues: [
"4|Sam|2012-02-10T00:00Z|2012-02-10T00:00Z",
"0|Wallace|1970-01-01T00:00Z|2012-02-10T00:00Z"
]
};
console.log(mapData(data));
//});
/*Expected Output [{"testNumber" : "4", "testName" : "Sam", "testDate1" : "2012-02-10T00:00Z", "testDate2" : "2012-02-10T00:00Z"},{"testNumber" : "0", "testName" : "Wallace", "testDate1" : "1970-01-01T00:00Z", "testDate2" : "2012-02-10T00:00Z"}]*/
Hit F12 in Chrome to see console, or open FireBug in FireFox or LadyBug in Opera, etc.
Related
I'm trying to perform MapReduce on this kind of data set:
{
"_id": "599861ce7ce78cd973746906",
"name": "Macias Rosario",
"col": [
{
"date": "15/03/2016",
"name": "MAGNEATO",
"amount": 313.86
},
{
"date": "08/08/2016",
"name": "FORTEAN",
"amount": 151.06
},
{
"date": "05/11/2014",
"name": "ECRATIC",
"amount": 291.68
}
]
}
Goal is to sum up all amount for name Macias Rosario. Currently I did with my code to group all by subelements this.col.name on this way:
mapper = Code("""
function() {
for (var index = 0; index < this.col.length; ++index) {
var col = this.col[index];
emit(col.name, col.amount );
}
}
""")
reducer = Code("""
function(key, values) {
var total = 0;
for( var i = 0; i < values.length; ++i){
total += values[i];
}
return value.price;
}
""")
result = collection.map_reduce(mapper, reducer, "myresult")
Has anyone have some idea how to reference, or group by this.name and not this.col.name because I don't know anymore and I'm driving nuts?
PS don't suggest me to use aggregate, did that way, want to try on this way also :)
Kind regards,
I hope the following code helps (works in pymongo as well)
This is my map function:
var mapFunction = function() {
for (var idx = 0; idx < this.col.length; idx++) {
var key = this.name;
var value = { amount : this.col[idx].amount };
emit(key, value);
}
};
And the following is my reduce function:
var reduceFunction = function(key, amountVl) {
reduceVal = { amount : 0 };
for (var idx = 0; idx < amountVl.length; idx++) {
reduceVal.amount += amountVl[idx].amount;
}
return reduceVal;
}
With your sample data it produces:
{ "_id" : "Macias Rosario", "value" : { "amount" : 756.6 } }
If I have the following:
var dataContainer = [
{ id : 1, value : 5, qty : 73, orders: 7 },
{ id : 2, value : 6.15, qty : 212, orders: 49},
{ id : 3, value : 12.11, qty : 29, orders : 6}
];
How do I update the value of the object using JavaScript? I have been trying the following:
function UpdateValues(passedId) {
var thisData = {};
for ( var i = 0; i < dataContainer.length; i++ ) {
thisData = dataContainer[i];
if (thisData.id == passedId) {
// I am updating the values in thisData
}
}
// Not sure what to do here in order to get thisData values back into dataContainer
}
So I tried to pop the dataContainer[i] and push the thisData back on but this didn't work. Unless I'm doing it incorrectly? What should I be doing here? I appreciate any help.
function UpdateValues(passedId, prop, newValue) {
var thisData = {};
for ( var i = 0; i < dataContainer.length; i++ ) {
thisData = dataContainer[i];
if (thisData.id == passedId) {
thisData[prop] = newValue;
}
}
}
//Change qty to 99999 for object with index of 1
UpdateValues(1, "qty", 99999);
I've added a fiddle that prints out the result as well: http://jsfiddle.net/4UH9e/
function UpdateValues(passedId) {
var thisData = {};
for ( var i = 0; i < dataContainer.length; i++ ) {
var data = dataContainer[i];
for (i in data) {
thisData[i] = data[i];
}
if (thisData.id == passedId) {
//Update the values in thisData.
}
}
//You still have the original data in dataContainer
}
I have these JavaScript entities: Item and Items.
var exports = {};
exports.Item = function(item) {
if (item) {
for (var attr in this.attributes) {
var value = item[attr];
if (value !== undefined) {
this.attributes[attr] = value;
}
}
}
return this;
};
exports.Item.prototype.attributes = {
_id: "",
title: ""
};
exports.Items = function(items) {
if (items && items.length > 0) {
for (var i = 0; i < items.length; i++) {
this.add(items[i]);
}
}
};
exports.Items.prototype.arr = [];
exports.Items.prototype.add = function(item) {
if (item) {
item = new exports.Item(item);
this.arr.push(item.attributes);
}
};
exports.Items.prototype.toJSON = function() {
var json = [];
for (var i = 0; i < this.arr.length; i++) {
json.push(this.arr[i]);
}
return json;
};
var i1 = new exports.Item({
_id: "1",
title: "1"
});
var i2 = new exports.Item({
_id: "2",
title: "2"
});
var i3 = new exports.Item({
_id: "3",
title: "3"
});
var items = new exports.Items([i1,i2,i3]);
console.log(items.toJSON());
There is a problem which I cannot find. When I execute the following code I get the last item 3 times instead of all the items.
I am sure the mistake is something small I cannot see. Maybe you can help me?
Member variables shouldn't be initialized in the prototype. Prototype variables will be shared across all instances. Instead, define the members in the constructor. So, instead of this:
exports.Items.prototype.arr = [];
Do this:
exports.Items = function(items) {
this.arr = []; // instance variable
if (items && items.length > 0) {
for (var i = 0; i < items.length; i++) {
this.add(items[i]);
}
}
};
I am converting JavaScript object to array but in result I am getting one null
here my code
<div id="a"></div>
Object.prototype.toArray = function(){
var arr = [];
for (var i in this) {
arr.push(this[i]);
}
return arr;
}
var providers = {
facebooklike: "Facebook Like",
facebookrecommend : "Facebook Recommend",
facebooksend : "Facebook Send",
twittertweet : "Twitter Tweet",
linkedinshare : "LinkedIn Share",
linkedinrecommend : "LinkedIn Recommend",
googleplusplusone : "Google+ +1",
googleplusshare : "Google+ Share"
};
var a = document.getElementById("a");
a.innerHTML = JSON.stringify(providers.toArray());
My result is
["Facebook Like","Facebook Recommend","Facebook Send","Twitter
Tweet","LinkedIn Share","LinkedIn Recommend","Google+ +1","Google+
Share",null]
Here is fiddle example
Add check for own properties (not inherited from the Object proptotype):
Object.prototype.toArray = function(){
var arr = [];
for (var i in this) {
if(this.hasOwnProperty(i))
arr.push(this[i]);
}
return arr;
}
Add hasOwnProperty check.
for (var i in this) {
if (this.hasOwnProperty(i)) {
arr.push(this[i]);
}
}
I have a generated JSON file that I would like to transform. Is there an easy way to transform the "id"/"value" form of this JSON to a proper key/value JSON object, without using any frameworks?
These lines:
"value":"chrome",
"id":"foo"
would convert to:
"foo": "chrome"
Input JSON:
{"row":[
{
"column":[
{
"value":"chrome",
"id":"foo"
},
{
"value":0,
"id":"bar"
},
{
"value":"baz1",
"id":"baz"
},
{
"value":0,
"id":"legacy"
}
]
},
{
"column":[
{
"value":"firefox",
"id":"foo"
},
{
"value":0,
"id":"bar"
},
{
"value":"baz2",
"id":"baz"
},
{
"value":0,
"id":"legacy"
}
]
}
]
}
Desired JSON:
{"row":[
{
"foo":"chrome",
"bar":0,
"baz":"baz1",
"legacy":0
},
{
"foo":"firefox",
"bar":0,
"baz":"baz2",
"legacy":0
}
]
}
Here is the solution:
var result = {"row": []}
for (var i = 0; i < input["row"].length; i++) {
var object = {};
var column = input["row"][i]["column"];
for (var j = 0; j < column.length; j++) {
object[column[j]["id"]] = column[j]["value"];
}
result.row.push(object);
}
console.log(result);
input variable refers to your initial JSON object.
var input = {"row":[
{
"column":[
...
here is my function, i was typing it out allready before ioseb posted his answer so i figured it post it as well, it's linted and everything
function transform(data) {
"use strict";
var x, i, row, column, colNumb, out = {rows : []}, rownum = data.row.length;
for (x = 0; x < rownum; x += 1) {
row = {};
column = data.row[x].column;
colNumb = column.length;
for (i = 0; i < colNumb; i += 1) {
row[column[i].id] = column[i].value;
}
out.rows.push(row);
}
return out;
}