I am trying to parse a TLV string and need to generate a nested object from that string.
const text = 'AA06ClaireCC04JackBB03TomEE05James'
The output needs to look like this:
"Acrobatic Artist": {
"AA": {
"Claire": {
"Curious Camper": {
"CC": {
"Jack": {
"Baddest Banana": {
"BB": {
"Tom": {
"Energetic Elephant": {
"EE": {
"James" : "LASTRECORD"
}
}
}
}
}
}
}
}
}
}
}
Here is what I currently have:
const map = {
AA: 'Acrobatic Artist',
BB: 'Baddest Banana',
CC: 'Curious Camper',
DD: 'Desperate Driver',
EE: 'Energetic Elephant'
}
function createJson(str) {
let json = {}
let remainingText = str
while(remainingText.length > 0) {
const tag = remainingText.substring(0, 2)
const len = remainingText.substring(2, 4)
const val = remainingText.substring(4, len)
const offset = tag.length + len.length + parseInt(len, 16)
remainingText = remainingText.substring(offset)
console.log('new text: ' + remainingText)
json[map[tag]] = {}
json[map[tag]][tag] = {}
json[map[tag]][tag][val] = {}
}
return json
}
But this just creates an object that looks like this:
{
Acrobatic Artist: {
AA: {
Claire: {}
}
},
Baddest Banana: {
BB: {
Tom: {}
}
},
Curious Camper: {
CC: {
Jack: {}
}
},
Energetic Elephant: {
EE: {
James: {}
}
}
}
Here is my fiddle:
https://jsfiddle.net/kzaiwo/y9m2h60t/8/
Note:
Please disregard the LASTRECORD part. I just added that to complete the key-value pair (for the last pair) in the above example. Thank you!
Thanks!
If you keep a reference to a prev value, which starts off as the original json object, you can then continuously update it and its children. When you're updating your object within the while loop you can update prev, and set it to the last child object that you create so that on the next iteration of your loop that particular child object will be updated to contain the new key-value pairs.
const map = {
AA: 'Acrobatic Artist',
BB: 'Baddest Banana',
CC: 'Curious Camper',
DD: 'Desperate Driver',
EE: 'Energetic Elephant'
};
const text = 'AA06ClaireCC04JackBB03TomEE05James';
function createJson(str) {
let json = {};
let prev = json;
let remainingText = str;
while (remainingText.length > 0) {
const tag = remainingText.substring(0, 2);
const len = remainingText.substring(2, 4);
const val = remainingText.substring(4, 4 + parseInt(len, 16));
const offset = tag.length + len.length + parseInt(len, 16);
remainingText = remainingText.substring(offset);
prev[map[tag]] = {};
prev[map[tag]][tag] = {};
prev = prev[map[tag]][tag][val] = {};
}
return json;
}
console.log(createJson(text));
Given the regular structure of your string (2-character code + 2-character number + characters), you can use a simple regex to split out the various parts.
From there you can (flat) map each section into an array of keys.
Finally, you can reduce-right the array to produce the result you want.
const map = {AA:"Acrobatic Artist",BB:"Baddest Banana",CC:"Curious Camper",DD:"Desperate Driver",EE:"Energetic Elephant"};
const text = "AA06ClaireCC04JackBB03TomEE05James";
// Parses a code, length and value from the start of the provided string
const parseSection = (str) => {
const [, code, valueLength] = str.match(/^(\w{2})([a-fA-F0-9]{2})/);
const length = parseInt(valueLength, 16) + 4;
return {
code,
length,
type: map[code],
value: str.slice(4, length),
};
};
// Iterates through the string, extracting sections until finished
const parseTlv = (str) => {
const sections = [];
while (str.length) {
const section = parseSection(str);
sections.push(section);
str = str.slice(section.length);
}
return sections;
};
// Map each section to a flat array of keys then reduce-right to form
// a tree structure
const lastRecord = {};
const result = parseTlv(text)
.flatMap(({ type, code, value }) => [type, code, value])
.reduceRight(
(obj, key) => ({
[key]: obj,
}),
lastRecord
);
console.log(result);
.as-console-wrapper { max-height: 100% !important; }
Here is a two part solution:
for() loop: create an array of items based on <tag><len><val> patterns
.reduce(): build the nested object from the items array
const input = 'AA06ClaireCC04JackBB03TomEE05James';
const tagMap = {
AA: 'Acrobatic Artist',
BB: 'Baddest Banana',
CC: 'Curious Camper',
DD: 'Desperate Driver',
EE: 'Energetic Elephant'
};
let items = [];
for(let i = 0; i < input.length; ) {
let tag = input.substring(i, i + 2);
let len = parseInt(input.substring(i + 2, i + 4), 16);
let val = input.substring(i + 4, i + 4 + len);
items.push([tag, val]);
i += 4 + len;
}
let result = {};
items.reduce((obj, arr) => {
const tag = arr[0];
const val = arr[1];
const name = tagMap[tag] || 'unknown';
//console.log(name, tag, val);
[name, tag, val].forEach(key => {
obj[key] = {};
obj = obj[key];
});
return obj;
}, result);
console.log(result);
Output:
{
"Acrobatic Artist": {
"AA": {
"Claire": {
"Curious Camper": {
"CC": {
"Jack": {
"Baddest Banana": {
"BB": {
"Tom": {
"Energetic Elephant": {
"EE": {
"James": {}
}
}
}
}
}
}
}
}
}
}
}
}
Note: the resulting object has an empty {} as the innermost value; you could replace that with "LASTRECORD" if needed
Related
How to use the name property in this object:
const obj = {
name: 'root/branch/subbranch/leaf',
value: 'my-value'
}
To create an object with the following format:
{
root: {
branch: {
subbranch: {
leaf: 'my-value'
}
}
}
}
You could do this using split and reduce
const obj = {
name: 'root/branch/subbranch/leaf',
value: 'my-value'
}
let newObj = {}
const parts = obj.name.split('/')
parts.reduce((prev, curr, i) => (
Object.assign(
prev,
{[curr]: i === parts.length - 1 ? obj.value : Object(prev[curr])}
),
prev[curr]
), newObj)
console.log(newObj)
I wrote a reciursive function and a wrapper to call it.
const obj = {
name: 'root/branch/subbranch/leaf',
value: 'my-value'
}
const recursiveNest = (result, value, arr, index = 0) => {
const path = arr[index]
if (index < arr.length - 1) {
result[path] = {}
index +=1;
recursiveNest(result[path], value, arr, index)
} else {
result[arr[index]] = value;
}
};
const createNestedObject = (obj, splitBy) => {
let result = {}
recursiveNest(result, obj.value, obj.name.split(splitBy))
return result;
}
console.log(createNestedObject(obj, '/'));
Lodash provides setWith(object, path, value, [customizer]):
const obj = {
name: 'root/branch/subbranch/leaf',
value: 'my-value'
}
console.log(_.setWith({}, obj.name.split('/'), obj.value, _.stubObject))
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.21/lodash.min.js"></script>
I want to total all same ID and assign a specific key
var ingredArray= [{"inventory_id":1,"pergram":222},{"inventory_id":1,"pergram":33},{"inventory_id":2,"pergram":424},{"inventory_id":2,"pergram":22},{"inventory_id":3,"pergram":400},{"inventory_id":5,"pergram":200}]
let deduction={};
ingredArray.forEach(function (item) {
if (deduction.hasOwnProperty(item.inventory_id)) {
deduction[item.inventory_id] = deduction[item.inventory_id] + parseFloat(item.pergram);
} else {
deduction[item.inventory_id] = parseFloat(item.pergram);
}
});
console.log(deduction);
this is the result of my code
{1: 255, 2: 446, 3: 400, 5: 200}
I want to achieve
{"inventory_id":1,"pergram":255},{"inventory_id":2,"pergram":446},{"inventory_id":3,"pergram":400},{"inventory_id":5,"pergram":200}
Try this
var ingredArray = [{ "inventory_id": 1, "pergram": 222 }, { "inventory_id": 1, "pergram": 33 }, { "inventory_id": 2, "pergram": 424 }, { "inventory_id": 2, "pergram": 22 }, { "inventory_id": 3, "pergram": 400 }, { "inventory_id": 5, "pergram": 200 }]
var helper = {};
let deduction = ingredArray.reduce(function (r, o) {
var key = o.inventory_id;
if (!helper[key]) {
helper[key] = Object.assign({}, o); // create a copy of o
r.push(helper[key]);
} else {
helper[key].pergram += o.pergram;
}
return r;
}, []);
console.log(deduction);
reduce over the array of objects building a new object of summed values based on key, and then grab the Object.values.
const data = [{"inventory_id":1,"pergram":222},{"inventory_id":1,"pergram":33},{"inventory_id":2,"pergram":424},{"inventory_id":2,"pergram":22},{"inventory_id":3,"pergram":400},{"inventory_id":5,"pergram":200}];
const out = data.reduce((acc, c) => {
// Grab the id and pergram variables from the
// new object in the iteration
const { inventory_id: id, pergram } = c;
// If the the accumulator object doesn't have a key that
// matches the id create a new new object, and set the
// pergram variable to zero
acc[id] = acc[id] || { inventory_id: id, pergram: 0 };
// And then add the pergram value to the
// pergram object property
acc[id].pergram += pergram;
// Return the accumulator for the next iteration
return acc;
}, {});
console.log(Object.values(out));
Use Map to store the object reference based on unique inventory_id and call Array.reduce() method over list of objects.
var ingredArray= [{"inventory_id":1,"pergram":222},{"inventory_id":1,"pergram":33},{"inventory_id":2,"pergram":424},{"inventory_id":2,"pergram":22},{"inventory_id":3,"pergram":400},{"inventory_id":5,"pergram":200}];
const processArray = (list) => {
const map = new Map();
return list.reduce((accumulator, obj) => {
const inventory = map.get(obj.inventory_id);
if (inventory) {
inventory.pergram += obj.pergram;
} else {
accumulator.push(obj);
map.set(obj.inventory_id, obj);
}
return accumulator;
}, []);
}
console.log(processArray(ingredArray));
We're trying to set nested object values based on dot notation strings.
Example input:
{
"bowtime": [
"30",
" 1",
" 3",
" 20"
],
"bowstate.levi.leviFlo.totalFloQuot": ".95",
"bowstate.crem.cremQuot": "79"
}
Desired output:
{
"bowstate": {
"levi": {
"leviFlo": {
"totalFloQuot": 0.95
}
},
"crem": {
"cremQuot": 79
}
},
"bowtime": [
"30",
" 1",
" 3",
" 20"
],
}
So far the code works fine, but it seems overly complex, and only allows for 4 layers of nesting. How can we simplify this code, and get it working for references with more than 4 layers of nesting:
const dayspace = {};
var keyArr = Object.keys(input);
for (key in keyArr) {
if ( keyArr[key].indexOf('.') > -1 ) {
var setArr = keyArr[key].split('.');
dayspace[setArr[0]] = dayspace[setArr[0]] || {}
for (var s = 0; s < setArr.length; s++) {
if (s == 1) {
if (setArr.length > s + 1) dayspace[setArr[0]][setArr[s]] = {}
else dayspace[setArr[0]][setArr[s]] = req.body[keyArr[key]]
}
if (s == 2) {
if (setArr.length > s + 1) dayspace[setArr[0]][setArr[1]][setArr[s]] = {}
else dayspace[setArr[0]][setArr[1]][setArr[s]] = req.body[keyArr[key]]
}
if (s == 3) {
if (setArr.length > s + 1) dayspace[setArr[0]][setArr[1]][setArr[2]][setArr[s]] = {}
else dayspace[setArr[0]][setArr[1]][setArr[2]][setArr[s]] = req.body[keyArr[key]]
}
if (s == 4) dayspace[setArr[0]][setArr[1]][setArr[2]][setArr[3]][setArr[s]] = req.body[keyArr[key]]
}
}
else {
dayspace[keyArr[key]] = req.body[keyArr[key]]
}
}
I'd split the key by . and use reduce to create all but the last nested value, if needed, and then assign the value to the last object created or found in the reduce callback:
const input = {
"bowtime": [
"30",
" 1",
" 3",
" 20"
],
"bowstate.levi.leviFlo.totalFloQuot": ".95",
"bowstate.crem.cremQuot": "79"
};
const output = Object.entries(input).reduce((outerObj, [key, val]) => {
if (!key.includes('.')) {
outerObj[key] = val;
return outerObj;
}
const keys = key.split('.');
const lastKey = keys.pop();
const lastObj = keys.reduce((a, key) => {
// Create an object at this key if it doesn't exist yet:
if (!a[key]) {
a[key] = {};
}
return a[key];
}, outerObj);
// We now have a reference to the last object created (or the one that already existed
// so, just assign the value:
lastObj[lastKey] = val;
return outerObj;
}, {});
console.log(output);
I have done similar things in my project. I have achieved it with a popular package called Flat. Link: https://github.com/hughsk/flat
var unflatten = require('flat').unflatten
unflatten({
'three.levels.deep': 42,
'three.levels': {
nested: true
}
})
// {
// three: {
// levels: {
// deep: 42,
// nested: true
// }
// }
// }
This package can make your nested structure flat and flatten structure nested as well. There are other useful methods there also. So it will be more flexible.
I think you should use it which will lead to less bugs in your project.
You could use Object.entires to get an array of key-value pairs within your object and then .reduce() your object keys by using .split(".") to get the single object properties into an array which you can then use to build your new object:
const obj = {
"bowtime": [
"30",
" 1",
" 3",
" 20"
],
"bowstate.levi.leviFlo.totalFloQuot": ".95",
"bowstate.crem.cremQuot": "79"
};
const res = Object.entries(obj).reduce((acc, [k, v]) => {
const keys = k.split('.');
let cur = acc;
keys.length > 1 && keys.forEach(ka => {
cur[ka] = cur[ka] || {};
cur = cur[ka];
});
cur[keys.pop()] = v;
return acc;
}, {});
console.log(res);
You could use a shorter approach by using a function for the splitted path to the value and generate new objects for it.
function setValue(object, path, value) {
var last = path.pop();
path.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
}
var object = { bowtime: ["30", " 1", " 3", " 20" ], "bowstate.levi.leviFlo.totalFloQuot": ".95", "bowstate.crem.cremQuot": "79" };
Object.entries(object).forEach(([key, value]) => {
if (!key.includes('.')) return;
setValue(object, key.split('.'), value);
delete object[key];
});
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have a two JSON something like below:
var obj1 = {
" name ":"rencho",
" age ":23,
" occupation ":"SE"
}
var obj2 = {
" name ":"manu",
" age ":23,
" country ":"india"
}
I want the expected output:
var result = {
"name":["rencho", "manu"],
"age":[23, 23],
"country":["-", "india"],
"occupation": ["SE", "-"],
}
However, I tried using below the code snippet:
let arrGlobal = []
arrGlobal.push(obj1);
arrGlobal.push(obj2);
let mergedResult = arrGlobal.reduce(function(r, e) {
return Object.keys(e).forEach(function(k) {
if(!r[k]) r[k] = [].concat(e[k])
else r[k] = r[k].concat(e[k])
}), r
}, {})
console.log(mergedResult);
But that one doesn't print - in json object. I would appreciate any kind of help from your side.
HELP WOULD BE APPRECIATED!!!
First get a list of all keys (needed in advance to check whether you need to add - while iterating), then use reduce to iterate over each object and add its values to the accumulator:
var obj1 = {
" name ":"rencho",
" age ":23,
" occupation ":"SE"
}
var obj2 = {
" name ":"manu",
" age ":23,
" country ":"india"
}
const arr = [obj1, obj2];
const allKeys = arr.reduce((keys, obj) => {
Object.keys(obj).forEach(key => keys.add(key))
return keys;
}, new Set());
const merged = arr.reduce((merged, obj) => {
allKeys.forEach((key) => {
if (!merged[key]) merged[key] = [];
merged[key].push(obj[key] || '-');
});
return merged;
}, {});
console.log(merged);
A slightly different approach by using a single loop for the outer array of objects and which generates all needed keys on the fly.
var obj1 = { name: "rencho", age: 23, occupation: "SE" },
obj2 = { name: "manu", age: 23, country: "india" },
hash = new Set,
result = {};
[obj1, obj2].forEach((o, length) => {
Object.keys(o).forEach(k => hash.add(k));
hash.forEach(k => {
result[k] = result[k] || Array.from({ length }).fill('-');
result[k].push(k in o ? o[k] : '-');
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
quick and dirty way:
function merge(a,b) {
var c = b
for (key in a){
c[key] = [c[key], a[key]]
}
console.log(c) //prints merged object
}
merge(obj1, obj2)
I have a javascript object that I need to flatten into a string so that I can pass as querystring, how would I do that? i.e:
{ cost: 12345, insertBy: 'testUser' } would become cost=12345&insertBy=testUser
I can't use jQuery AJAX call for this call, I know we can use that and pass the object in as data but not in this case. Using jQuery to flatten to object would be okay though.
Thank you.
Here's a non-jQuery version:
function toQueryString(obj) {
var parts = [];
for (var i in obj) {
if (obj.hasOwnProperty(i)) {
parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i]));
}
}
return parts.join("&");
}
You want jQuery.param:
var str = $.param({ cost: 12345, insertBy: 'testUser' });
// "cost=12345&insertBy=testUser"
Note that this is the function used internally by jQuery to serialize objects passed as the data argument.
My ES6 version (pure Javascript, no jQuery):
function toQueryString(paramsObject) {
return Object
.keys(paramsObject)
.map(key => `${encodeURIComponent(key)}=${encodeURIComponent(paramsObject[key])}`)
.join('&')
;
}
This is an old question, but at the top of Google searches, so I'm adding this for completeness.
If 1) you don't want to user jQuery, but 2) you want to covert a nested object to a query string, then (building off of Tim Down and Guy's answers), use this:
function toQueryString(obj, urlEncode) {
//
// Helper function that flattens an object, retaining key structer as a path array:
//
// Input: { prop1: 'x', prop2: { y: 1, z: 2 } }
// Example output: [
// { path: [ 'prop1' ], val: 'x' },
// { path: [ 'prop2', 'y' ], val: '1' },
// { path: [ 'prop2', 'z' ], val: '2' }
// ]
//
function flattenObj(x, path) {
var result = [];
path = path || [];
Object.keys(x).forEach(function (key) {
if (!x.hasOwnProperty(key)) return;
var newPath = path.slice();
newPath.push(key);
var vals = [];
if (typeof x[key] == 'object') {
vals = flattenObj(x[key], newPath);
} else {
vals.push({ path: newPath, val: x[key] });
}
vals.forEach(function (obj) {
return result.push(obj);
});
});
return result;
} // flattenObj
// start with flattening `obj`
var parts = flattenObj(obj); // [ { path: [ ...parts ], val: ... }, ... ]
// convert to array notation:
parts = parts.map(function (varInfo) {
if (varInfo.path.length == 1) varInfo.path = varInfo.path[0];else {
var first = varInfo.path[0];
var rest = varInfo.path.slice(1);
varInfo.path = first + '[' + rest.join('][') + ']';
}
return varInfo;
}); // parts.map
// join the parts to a query-string url-component
var queryString = parts.map(function (varInfo) {
return varInfo.path + '=' + varInfo.val;
}).join('&');
if (urlEncode) return encodeURIComponent(queryString);else return queryString;
}
Use like:
console.log(toQueryString({
prop1: 'x',
prop2: {
y: 1,
z: 2
}
}, false));
Which outputs:
prop1=x&prop2[y]=1&prop2[z]=2
Here is another non-jQuery version that utilizes lodash or underscore if you're already using one of those libraries:
var toQueryString = function(obj) {
return _.map(obj,function(v,k){
return encodeURIComponent(k) + '=' + encodeURIComponent(v);
}).join('&');
};
^ I wrote that 5 years ago. An updated and more succinct version of this would now (Oct 2019) be:
var input = { cost: 12345, insertBy: 'testUser' };
Object.entries(input)
.map(([k,v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join('&');
// cost=12345&insertBy=testUser
Check that the runtime that you're targeting supports Object.entries() or that you're using a transpiler like Babel or TypeScript if it doesn't.
Try the $.param() method:
var result = $.param({ cost: 12345, insertBy: 'testUser' });
General JavaScript:
function toParam(obj) {
var str = "";
var seperator = "";
for (key in obj) {
str += seperator;
str += enncodeURIComponent(key) + "=" + encodeURIComponent(obj[key]);
seperator = "&";
}
return str;
}
toParam({ cost: 12345, insertBy: 'testUser' })
"cost=12345&insertBy=testUser"
Another version:
function toQueryString(obj) {
return Object.keys(obj).map(k => {
return encodeURIComponent(k) + "=" + encodeURIComponent(obj[k])
})
.join("&");
}
var myObj = { cost: 12345, insertBy: 'testUser' },
param = '',
url = 'http://mysite.com/mypage.php';
for (var p in myObj) {
if (myObj.hasOwnProperty(p)) {
param += encodeURIComponent(p) + "=" + encodeURIComponent(myObj[p]) + "&";
}
}
window.location.href = url + "?" + param;
you can use this
function serialize(obj)
{
let str = []
for(var p in obj)
{
if(obj.hasOwnProperty(p)) str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]))
}
return str.join('&')
}
try on JSFiddle on this link https://jsfiddle.net/yussan/kwmnkca6/
ES6 version of Jrop's answer (also parses nested params)
const toQueryString = (obj, urlEncode = false) => {
if (!obj) return null;
const flattenObj = (x, path = []) => {
const result = [];
Object.keys(x).forEach((key) => {
if (!Object.prototype.hasOwnProperty.call(x, key)) return;
const newPath = path.slice();
newPath.push(key);
let vals = [];
if (typeof x[key] === 'object') {
vals = flattenObj(x[key], newPath);
} else {
vals.push({ path: newPath, val: x[key] });
}
vals.forEach((v) => {
return result.push(v);
});
});
return result;
};
let parts = flattenObj(obj);
parts = parts.map((varInfo) => {
if (varInfo.path.length === 1) {
varInfo.path = varInfo.path[0]; // eslint-disable-line no-param-reassign
} else {
const first = varInfo.path[0];
const rest = varInfo.path.slice(1);
varInfo.path = `${first}[${rest.join('][')}]`; // eslint-disable-line no-param-reassign
}
return varInfo;
});
const queryString = parts.map((varInfo) => {
return `${varInfo.path}=${varInfo.val}`;
}).join('&');
if (urlEncode) {
return encodeURIComponent(queryString);
}
return queryString;
};
Using Lodash library it can be done as:
let data = {}
_.map(data, (value, key) => `${key}=${value}`)
.join("&");
Note that this library has been imported as:
window._ = require('lodash');