Javascript object transform - javascript

I want to transform this object so that I can call it that way
cars.ox, bikes.ox
var baseValue = [
{
'2014-12-01': {
'cars;ox;2014-12-01':100,
'cars;ot;2014-12-01':150,
'bikes;ox;2014-12-01':50,
'bikes;ot;2014-12-01':80
},
'2014-12-02': {
'cars;ox;2014-12-02':100,
'cars;ot;2014-12-02':150,
'bikes;ox;2014-12-02':50,
'bikes;ot;2014-12-02':80
}
}
]
I try do this in many ways, but at the end i completely lost all hope.
var category = []
var obj = baseValue[0]
Object.keys(obj).forEach(function(key) {
var dane = obj[key]
Object.keys(dane).forEach(function(key) {
splitted = key.split(';')
var category = splitted[0]
var serviceName = splitted[1];
})
})
I would be grateful if anyone help me with this

I think you were close, you just need to create objects if they do not exist for the keys you want. Perhaps something like this.
var obj = baseValue[0]
var result = {};
Object.keys(obj).forEach(function(key) {
var dane = obj[key]
Object.keys(dane).forEach(function(key) {
splitted = key.split(';')
var category = splitted[0]
var serviceName = splitted[1];
if(!result[category]) {
result[category] = {};
}
if(!result[category][serviceName]) {
result[category][serviceName] = [];
}
result[category][serviceName].push(dane[key]);
})
});
http://jsfiddle.net/6c5c3qwy/1/
(The result is logged to the console.)

Related

Is there a way to convert an object key containing an array to an object?

Here is my current object:
{"or_11[and_3][gt#last_closed_sr]":"2019-06-18"}
I would like it to look like:
{
"or_11": {
"and_3": {
"gt#last_closed_sr": "2019-06-18",
}
}
}
What is the best way to do this?
In general the answer to poorly formatted data is to fix the formatter, not to implement a parser. However, I've worked with systems that encode data like that, so here's a parser.
function parseSquareSeparatedData(data) {
const result = {};
Object.keys(data).forEach((key) => {
const keyParts = key.replace(/]/g, "").split("[");
const last = keyParts.pop();
let resultPointer = result;
keyParts.forEach((keyPart) => {
if (!(keyPart in resultPointer)) {
resultPointer[keyPart] = {};
}
resultPointer = resultPointer[keyPart];
})
resultPointer[last] = input[key];
})
return result;
}
let str = '"or_11[and_3][gt#last_closed_sr]":"2019-06-18"';
let first = str.replace(/"/g, '').match(/\w+/)[0];
let pattern = /\[(.+?)\]/g;
let matches = [];
let match;
while(match = pattern.exec(str)) {
matches.push(match[1])
}
let val = str.replace(/"/g, '').split(':')[1];
let obj = {
[first]: {
[matches[0]]: {
[matches[1]]: val
}
}
}
console.log(obj)

JavaScript build nested array from string values

From my data source I am getting values like;
USA |Arizona
USA |Florida
UK |England |Northamptonshire
UK |England |Derbyshire
UK |Wales |Powys
Switzerland|Lucern
These are flat text values that repeat in a column.
I need to build them dynamically into nested array
source: [
{title: "USA", children: [
{title: "Arizona"},
{title: "Florida"}
]}
],
As per https://github.com/mar10/fancytree/wiki/TutorialLoadData
Unfortunately my brain has stopped working today I am can't see a elegant way.
Any pointers would be most gratefully appreciated.
So I solved this eventually using a post from Oskar
function getNestedChildren(arr, parent) {
var out = []
for(var i in arr) {
if(arr[i].parent == parent) {
var children = getNestedChildren(arr, arr[i].id)
if(children.length) {
arr[i].children = children
}
out.push(arr[i])
}
}
return out
}
http://oskarhane.com/create-a-nested-array-recursively-in-javascript/
This builds the nested array.
To ensure inferred values were present (e.g. USA which is in the hierarchy but is not a unique value).
var CountryArray = CountryText.split("|");
// Variables to hold details of each section of the Country path being iterated
var CountryId = '';
var CountryParentPrefix = '';
var CountryParent = '';
// Iterate each section of the delimeted Country path and ensure that it is in the array
for(var i in CountryArray)
{
var CountryId = CountryParentPrefix+CountryArray[i];
// Find the Country id in the array / add if necessary
var result = FlatSource.filter(function (Country) { return Country.id == CountryId });
if (result.length == 0) {
// If the Country is not there then we should add it
var arrCountry = {title:CountryArray[i], parent:CountryParent, id:CountryId};
FlatSource.push(arrCountry);
}
// For the next path of the heirarchy
CountryParent = CountryId;
CountryParentPrefix = CountryId+'|';
}
I did not use Sven's suggestion but I suspect that it is equally valid.
Turn it to JSON:
var str = '"USA|Arizona","USA|Florida","UK|LonelyIsland","UK|England|Northamptonshire","UK|England|Derbyshire","UK|Wales|Powys","UK|England|London|Soho","Switzerland|Lucern';
var jsonStr = "[[" + str.replace(/,/g,'],[') + "\"]]";
jsonStr = jsonStr.replace(/\|/g,'","');
var nested = JSON.parse(jsonStr);
Then play with parents and children.
function findObject(array, key, value) {
for (var i=0; i<array.length; i++) {
if (array[i][key] === value) {
return array[i];
}
}
return null;
}
function obj(arr){
this.title = arr.shift();
}
obj.prototype.addChild = function(arr){
var tmp = new obj(arr);
if(typeof this.children === 'undefined'){
this.children = new Array();
result = this.children[this.children.push(tmp)-1];
}else{
result = findObject(this.children, 'title', tmp.title);
if(!result)
result = this.children[this.children.push(tmp)-1];
}
return result;
}
obj.prototype.addChildren = function(arr){
var obje = this;
while(arr.length>0)
obje = obje.addChild(arr);
}
var finArr = [];
for(i=0; i<nested.length; i++){
var recc = new obj(nested[i]);
if(oldObj = findObject(finArr, 'title', recc.title)){
oldObj.addChildren(nested[i]);
}else{
if(nested[i].length>0)
recc.addChildren(nested[i]);
finArr.push(recc);
}
}
console.log('------------------------------------------')
console.log(JSON.stringify(finArr));
console.log('--------------------The End---------------')

Creating deep-nested objects in Javascript

When loading JSON from a server, I need to create objects. The objects do not always exist beforehand.Therefore I have to check that each level exists before adding a new level. Is there a better way to do this, then the following way:
var talkerId = commentDB.val().to;
var commentId = commentDB.val().id
if (!store.talkers.hasOwnProperty(talkerId)) {
store.talkers[talkerId] = {}
}
if (!store.talkers[talkerId].hasOwnProperty(comments)) {
store.talkers[talkerId] = { comments: {} };
}
if (!store.talkers[talkerId].comments.hasOwnProperty(commentId)) {
store.talkers[talkerId].comments[commentId] = {}
}
store.talkers[talkerId].comments[commentId].author = commentDB.val().author;
You cour reduce the keys by using the object an check if the key exist. if not create a new property with an empty object.
var dbValue = commentDB.val();
[dbValue.to, 'comments', dbValue.id].reduce(
(o, k) => o[k] = o[k] || {},
store.talkers
).author = commentDB.val().author;
Why don't you create a function
function checkAndCreateProperty(arr, baseVar) {
for(var i = 0; i < arr.length; i++) {
if (!baseVar.hasOwnProperty(arr[i])) {
baseVar[arr[i]] = {};
}
baseVar = baseVar[arr[i]];
}
}
checkAndCreateProperty(["talkerId", "comments", commentDB.val().id, commentDB.val().author], store.talkers)
After the suggestion of #31piy I went for the most simple solution:
using lodash _.set
var talkerId = commentDB.val().to;
var commentId = commentDB.val().id;
_.set(store.talkers, '[' + talkerId + '].comments[' + commentId + '].author', commentDB.val().author)

Trouble iterating through an object

I have an object that looks like this:
salesDetails:{ "1":{
"date":"06/22/2014",
"amount":"45",
"currency":"CAD",
"productID":"23",
"status":1},
"2":{
"date":"06/22/2014",
"amount":"120",
"currency":"USD",
"productID":"23",
"status":1},
"3":{
"date":"06/23/2014",
"amount":"100",
"currency":"USD",
"productID":"21",
"status":2},
"4":{
"date":"06/23/2014",
"amount":"250",
"currency":"CAD",
"productID":"25",
"status":1},
"5":{
"date":"06/23/2014",
"amount":"180",
"currency":"USD",
"productID":"24",
"status":1}
}
What i am trying to do is to get all the amount per currency of all that has status of "1" and put it in an object that should look like this:
perCurrency: {
"CAD":{
"0":"45",
"1":"250"},
"USD":{
"0":"120",
"1":"180"}
}
I was able to put all the currency in an object but I'm having trouble with the amount, the last amount from the object overlaps the previous one. I keep on getting {"CAD":{"1":"250"},"USD":{"1":"180"}} Here's my code so far.
function countPerCurrency(){
var currencyArray = new Array();
var perCurrency = {};
var totalSales = Object.size(salesDetails);
for(var i=1; i <= totalSales; i++){
var currency = salesDetails[i]["currency"];
var amount = salesDetails[i]["amount"];
var status = salesDetails[i]["status"];
var totalCurrency = Object.size(currencyAmount[currency]);
var currencyCtr = {};
if(status == 1){
if(!inArray(currency, currencyArray)){
currencyArray.push(currency);
currencyCtr[totalCurrency] = amount;
perCurrency[currency] = currencyCtr;
} else {
var currencyAdd = {};
currencyAdd[totalCurrency] = amount;
perCurrency[currency] = currencyAdd;
}
}
}
}
I know it might seem easy, but I'm lost here.. TIA! :)
The previously accepted answer uses an array of values, whereas you asked for an object. Here's an object version:
var perCurrency = {};
var currencyCount = {};
Object.keys(salesDetails).forEach(function(key) {
var obj = salesDetails[key];
var currency;
if (obj.status == 1) {
currency = obj.currency;
// If this is first for this currency, add it to objects
if (!currencyCount[currency]) {
currencyCount[currency] = 0;
perCurrency[currency] = {};
}
// Add currency values
perCurrency[currency][currencyCount[currency]++] = obj.amount;
}
});
BTW, this has nothing to do with jQuery.
Note that Object.keys is ES5 so may need a polyfill for older browsers, see MDN:Object.keys for code.
try something like this
function countPerCurrency(){
var perCurrency = {};
var totalSales = Object.size(salesDetails);
for(var i=1; i <= totalSales; i++){
var currency = salesDetails[i]["currency"];
var amount = salesDetails[i]["amount"];
var status = salesDetails[i]["status"];
if(status == '1'){
if(perCurrency.hasOwnProperty(currency)){
// if currency already present than get currency array.
var currency_arr = perCurrency[currency];
// add new value to existing currency array.
currency_arr.push(amount);
}else{
// if currency not present than create currency array and add first value;
var currency_arr = [];
currency_arr.push(amount);
// add newly created currency array to perCurrency object
perCurrency[currency] = currency_arr;
}
}
}
console.log(perCurrency);
}
output
perCurrency: {
"CAD":["45","250"],
"USD":["120","180"],
}
I have created currency array instead of key value pair
Change your code like this, i have simplified your things,
function countPerCurrency() {
var perCurrency = {};
var currencyArray = [];
for(i in salesDetails)
{
if(!perCurrency.hasOwnProperty(salesDetails[i].currency) && salesDetails[i].status === "1")
perCurrency[salesDetails[i].currency] = [];
if(salesDetails[i].status === "1")
{
currencyArray = perCurrency[salesDetails[i].currency];
currencyArray.push(salesDetails[i].amount);
perCurrency[salesDetails[i].currency] = currencyArray;
}
}
}
sorry for the late conversation anyway try like this use .each()
var CAD = new Array();
var USD = new Array();
$.each(salesDetails, function (i, value) {
if (value.status == 1) {
if (value.currency == "CAD") {
CAD.push(value.amount);
} else if (value.currency == "USD") {
USD.push(value.amount);
}
}
});
var perCurrency = {
"CAD": CAD,
"USD": USD
}
Demo

Build object in JavaScript from PHP form input name

There are a couple of similar questions but none covers the case when a string looks like some-name[][some-key]. I have tried JSON.parse('some-name[][some-key]'); but it doesn't parse it.
Is there a way to convert such string to a JavaScript object that will look like { 'some-name': { 0: { 'some-key': '' } } }?
This is a name of a form field. It's normally parsed by PHP but I'd like to parse it with JavaScript the same way. I basically have <input name="some-name[][some-key]"> and I'd like to convert that to var something = { 'some-name': { 0: { 'some-key': VALUE-OF-THIS-FIELD } } }.
Try this:
JSON.parse('{ "some-name": [ { "some-key": "" } ] }');
I don't know exactly how you're doing this, but assuming they are all that format (name[][key]) and you need to do them one by one - this works for me:
var fieldObj = {};
function parseFieldName(nameStr)
{
var parts = nameStr.match(/[^[\]]+/g);
var name = parts[0];
var key = typeof parts[parts.length-1] != 'undefined' ? parts[parts.length-1] : false;
if(key===false) return false;
else
{
if(!fieldObj.hasOwnProperty(name)) fieldObj[name] = [];
var o = {};
o[key] = 'val';
fieldObj[name].push(o);
}
}
parseFieldName('some-name[][some-key]');
parseFieldName('some-name[][some-key2]');
parseFieldName('some-name2[][some-key]');
console.log(fieldObj); //Firebug shows: Object { some-name=[2], some-name2=[1]} -- stringified: {"some-name":[{"some-key":"val"},{"some-key2":"val"}],"some-name2":[{"some-key":"val"}]}
o[key] = 'val'; could of course be changed to o[key] = $("[name="+nameStr+"]").val() or however you want to deal with it.
Try this:
var input = …,
something = {};
var names = input.name.match(/^[^[\]]*|[^[\]]*(?=\])/g);
for (var o=something, i=0; i<names.length-1; i++) {
if (names[i])
o = o[names[i]] || (o[names[i]] = names[i+1] ? {} : []);
else
o.push(o = names[i+1] ? {} : []);
}
if (names[i])
o[names[i]] = input.value;
else
o.push(input.value);
Edit: according to your updated example, you can make something like this (view below). This will work - but only with the current example.
var convertor = function(element) {
var elementName = element.getAttribute('name');
var inpIndex = elementName.substring(0, elementName.indexOf('[')),
keyIndex = elementName.substring(elementName.lastIndexOf('[') + 1, elementName.lastIndexOf(']'));
var strToObj = "var x = {'" + inpIndex + "': [{'" + keyIndex + "': '" + element.value + "'}]}";
eval(strToObj);
return x;
};
var myObject = convertor(document.getElementById('yourInputID'));
Example here: http://paulrad.com/stackoverflow/string-to-array-object.html
(result is visible in the console.log)
old response
Use eval.. but your string must have a valid javascript syntax
So:
var str = "arr[][123] = 'toto'";
eval(str);
console.log(arr);
Will return a syntax error
Valid syntax will be:
var str = "var arr = []; arr[123] = 'toto'";
var x = eval(str);
console.log(arr);

Categories

Resources