Optimizing a group by function in Javascript - javascript

I was looking for a way to group an array of object by a field.
I found a very useful answer in the comments of this answer (by #tomitrescak : https://stackoverflow.com/a/34890276/7652464
function groupByArray(xs, key) {
return xs.reduce(function (rv, x) {
let v = key instanceof Function ? key(x) : x[key];
let el = rv.find((r) => r && r.key === v);
if (el) {
el.values.push(x);
}
else {
rv.push({ key: v, values: [x] });
}
return rv; }, []);
}
Which can be used as following
console.log(groupByArray(myArray, 'type');
This function works perfect, however, my array contains objects with embedded fields.
I would like to use the the function as following
console.log(groupByArray(myArray, 'fullmessage.something.somethingelse');
I already have a function for extracting the embedded fields which works.
function fetchFromObject(obj, prop) {
if(typeof obj === 'undefined') {
return '';
}
var _index = prop.indexOf('.')
if(_index > -1) {
return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
}
return obj[prop];
}
Which can be used as following
var obj = { obj2 = { var1 = 2, var2 = 2}};
console.log(fetchFromObject(obj, 'obj2.var2')); //2
Can somebody help my to implement my function into the the group function.

You could change the line
let v = key instanceof Function ? key(x) : x[key];
into
let v = key instanceof Function ? key(x) : fetchFromObject(x, key);
for getting a value of an arbitrary nested key.

function groupBy(arr,props){
var props=props.split(".");
var result=[];
main:for(var i=0;i<arr.length;i++){
var value=arr[i];
for(var j=0;j<props.length;j++){
value=value[props[j]];
if(!value) continue main;
}
result.push(value);
}
return result;
}
Usecase:
groupBy({a:{b:2}},{a:{b:undefined}},{a:{b:3}},"a.b")//returns [2,3]

Related

Create a JavaScript object from keys which are dot separated in another object

I have a requirement where I have an object like obj={ 'a.b.c' : d }
and I would like it to get converted to {a:{b:{c:d}}}
Is there any way I can achieve this in JavaScript?
Here's a solution (EDITED: code is more complex than before but it gives the result you want, let me know if something doesn't work):
var obj = {
'a.b.c': 22,
'a.b.d.e': 42
}
var newObj = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var keyList = key.split('.');
newObj = generateNewObject(keyList, keyList.length - 1, newObj, obj[key]);
}
}
console.log(newObj);
function generateNewObject(keys, index, existingObj, value) {
if (index < 0) {
return value;
}
var lastKey = keys[index--];
var existingProperty = getProperty(existingObj, lastKey);
if (existingProperty != null && !objectsAreEqual(existingProperty, value)) {
var valueKey = keys[index + 2];
existingProperty[lastKey][valueKey] = value[valueKey];
value = existingProperty;
} else {
var subObj = {};
subObj[lastKey] = value;
value = subObj;
}
return generateNewObject(keys, index, existingObj, value);
}
function objectsAreEqual(obj1, obj2) {
for (var key in obj1) {
if (obj1.hasOwnProperty(key)) {
var prop = getProperty(obj2, key);
if (prop == null) {
return false;
}
}
}
return true;
}
function getProperty(obj, keyDesired) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
if (key === keyDesired) {
return obj;
} else {
var prop = getProperty(obj[key], keyDesired);
if (prop != null) {
return prop;
}
}
}
}
return null;
}
I don't know why you would have an object named that way, but this code will do the trick for each key in an object. This will not work correctly on nested objects such as {'a' : { 'b' { 'c' : {{'d' : 'e'}}}}}. You would have to repeat the for-loop part each time the value is a JavaScript object.
EDIT
I modified the code so it recognizes when two properties are the same such as the example { 'a.b.c' : 22 }, 'a.b.c.d.e' : 42. Sorry if it is hard to go through, but basically the generateNewObject method is the real meat of it. The two functions below it are just helper methods.
Array.reduce mostly is a good choice when it comes to handling/transforming of more complex data structures. An approach that solves the given problem generically whilst taking edge cases into account then might look similar to the next provided example ...
var
d = 'd',
q = 'q',
obj = {
'i.k.l.m.n.o.p' : q,
'a.b.c' : d,
'foo' : 'bar',
'' : 'empty'
};
function parseIntoNestedTypes(type) {
return Object.keys(type).reduce(function (collector, integralKey) {
var
nestedType = collector.target,
fragmentedKeyList = integralKey.split('.'),
nestedTypeRootKey = fragmentedKeyList.shift(),
nestedTypeEndValue = collector.source[integralKey];
if (fragmentedKeyList.length === 0) {
nestedType[nestedTypeRootKey] = nestedTypeEndValue;
} else {
nestedType[nestedTypeRootKey] = fragmentedKeyList.reduce(function (collector, key, idx, list) {
var
partialType = collector.partialType || collector.type;
if (idx < (list.length - 1)) {
partialType[key] = {};
} else {
partialType[key] = collector.value;
}
collector.partialType = partialType[key];
return collector;
}, {
value : nestedTypeEndValue,
type : {}
}).type;
}
return collector;
}, {
source: type,
target: {}
}).target;
}
console.log('parseIntoNestedTypes :: type', JSON.stringify(obj));
console.log('parseIntoNestedTypes :: nestedType', JSON.stringify(parseIntoNestedTypes(obj)));
console.log('parseIntoNestedTypes :: type, nestedType : ', obj, parseIntoNestedTypes(obj));

How to write a function that inlines object properties

I have the following object:
var ob = {
view: {
name: 'zpo',
params: {
taskId: 3,
zuka: 'v'
}
}
}
I need to have this object in the following form:
{
"view.name":"zpo",
"view.params.taskId":3,
"view.params.zuka":"v"
}
I have written a function that can do that, but the problem is that it requires external variables passed to it. Here is this function:
function inline(o, result, container) {
for (var p in o) {
if (typeof o[p] === "object") {
inline(o[p], result.length > 0 ? result+'.'+p : p, container);
} else {
container[result + '.' + p] = o[p];
}
}
}
var ob = {
view: {
name: 'zpo',
params: {
taskId: 3,
zuka: 'v'
}
}
}
var c = {};
var r = inline(ob, '', c);
Is there any way to write this function to return correct result without the need to pass result and container external variables?
If i understood you correctly, you want to avoid to call your inline() function with "empty" params.
You could catch this case in your function directly:
function inline(o, result, container) {
result = result || '';
container = container || {};
...
}
var r = inline(ob);
you would still need this params for the recursive part of your function.
Here is a version that does not require any parameters.
// Return an array containing the [key, value] couples of an object.
const objEntries = o => Object.keys(o).map(k => [k, o[k]]);
// Create an object from an array of [key, value] couples.
const entriesObj = (entries, init={}) => entries.reduce((result, [key, val]) => {
result[key] = val;
return result;
}, init);
// Reduce on the object entries (as returned by objEntries) with an empty object as
// initialiser.
const inline = (o) => objEntries(o).reduce((result, [key, val]) => {
if(val instanceof Object){
// If the value is an object, recursively inline it.
const inlineVal = inline(val);
// Prefix each property names of inlineVal with the key of val and add the
// properties to the result object.
entriesObj(
objEntries(inlineVal).map(([subK, subVal]) => [key + '.' + subK, subVal]),
result
);
} else {
// If val is not an object, just add it to the result as is.
result[key] = val;
}
// Return the result.
return result;
}, {});
var ob = {
view: {
name: 'zpo',
params: {
taskId: 3,
zuka: 'v'
}
}
}
var r = inline(ob);
console.log(r);
I used arrow functions and destructuring. Old browsers won't support it. If you need to support them, just replace the arrow functions with regular functions and manually destructure the arguments.
javascript is awesome!
function inline(o, result, container) {
result = result || '';
container = container || {};
for (var p in o) {
if (typeof o[p] === "object") {
inline(o[p], result.length > 0 ? result+'.'+p : p, container);
} else {
container[result + '.' + p] = o[p];
}
}
}
var r = inline(ob);

JS getting value of object with key starting with a string

Is there a quick way to get the value of a key starting with a certain string?
Example :
var obj = {
"key123" : 1,
"anotherkey" : 2
}
obj['key1'] // would return 1
obj['ano'] // would return 2
Thanks
You can create a helper function
function findValueByPrefix(object, prefix) {
for (var property in object) {
if (object.hasOwnProperty(property) &&
property.toString().startsWith(prefix)) {
return object[property];
}
}
}
findValueByPrefix(obj, "key1");
As Kenney commented, the above function will return first match.
You could use find on the entries of the object. IF there's a key which starts with, access the index at 1 to get the value.
Object.entries(o).find(([k,v]) => k.startsWith(part))?.[1]
Here's a snippet:
const getValue = (part, o) => Object.entries(o).find(([k, v]) => k.startsWith(part))?.[1]
const obj = {
"key123": 1,
"anotherkey": 2
}
console.log(
getValue('key', obj),
getValue('ano', obj),
getValue('something', obj),
)
Search for the first match of the property name which begins with specified string:
var obj = {
"key123": 1,
"anotherkey": 2,
"somekey" : 3
};
function getObjectValueByPartialName(obj, name){
if (typeof obj !== "object") {
throw new Error("object is required!");
}
for (var prop in obj) {
if (prop.indexOf(name) === 0){
return obj[prop];
}
}
return "no such property!";
}
console.log(getObjectValueByPartialName(obj, 'some')); // output: 3
console.log(getObjectValueByPartialName(obj, 'key1')); // output: 1
We could use the following one-line generic custom method
var obj = {
"key123" : 1,
"anotherkey" : 2
};
const getObjPropForMatchPrefixKey = (object,prefix) => Object.keys(object).filter(item => item.toString().startsWith(prefix))[0];
console.log(obj[getObjPropForMatchPrefixKey(obj,'an')]);
console.log(obj[getObjPropForMatchPrefixKey(obj,'key')]);

Convert complex JavaScript object to dot notation object

I have an object like
{ "status": "success", "auth": { "code": "23123213", "name": "qwerty asdfgh" } }
I want to convert it to dot notation (one level) version like:
{ "status": "success", "auth.code": "23123213", "auth.name": "qwerty asdfgh" }
Currently I am converting the object by hand using fields but I think there should be a better and more generic way to do this. Is there any?
Note: There are some examples showing the opposite way, but i couldn't find the exact method.
Note 2: I want it for to use with my serverside controller action binding.
You can recursively add the properties to a new object, and then convert to JSON:
var res = {};
(function recurse(obj, current) {
for(var key in obj) {
var value = obj[key];
var newKey = (current ? current + "." + key : key); // joined key with dot
if(value && typeof value === "object") {
recurse(value, newKey); // it's a nested object, so do it again
} else {
res[newKey] = value; // it's not an object, so set the property
}
}
})(obj);
var result = JSON.stringify(res); // convert result to JSON
Here is a fix/hack for when you get undefined for the first prefix. (I did)
var dotize = dotize || {};
dotize.parse = function(jsonobj, prefix) {
var newobj = {};
function recurse(o, p) {
for (var f in o)
{
var pre = (p === undefined ? '' : p + ".");
if (o[f] && typeof o[f] === "object"){
newobj = recurse(o[f], pre + f);
} else {
newobj[pre + f] = o[f];
}
}
return newobj;
}
return recurse(jsonobj, prefix);
};
You can use the NPM dot-object (Github) for transform to object to dot notation and vice-versa.
var dot = require('dot-object');
var obj = {
id: 'my-id',
nes: { ted: { value: true } },
other: { nested: { stuff: 5 } },
some: { array: ['A', 'B'] }
};
var tgt = dot.dot(obj);
Produces
{
"id": "my-id",
"nes.ted.value": true,
"other.nested.stuff": 5,
"some.array[0]": "A",
"some.array[1]": "B"
}
const sourceObj = { "status": "success", "auth": { "code": "23123213", "name": "qwerty asdfgh" } }
;
const { auth, ...newObj } = sourceObj;
const resultObj = {
...newObj,
..._.mapKeys(auth, (val, key) => `auth.${key}`)
}
// function approach
const dotizeField = (obj, key) => {
const { ...newObj } = sourceObj;
delete newObj[key];
return {
...newObj,
..._.mapKeys(obj[key], (val, subKey) => `${key}.${subKey}`)
}
}
const resultObj2 = dotizeField(sourceObj, 'auth');
console.log(sourceObj, resultObj, resultObj2);
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.20/lodash.min.js"></script>
i have done some fix:
export function toDotNotation(obj,res={}, current='') {
for(const key in obj) {
let value = obj[key];
let newKey = (current ? current + "." + key : key); // joined key with dot
if(value && typeof value === "object") {
toDotNotation(value,res, newKey); // it's a nested object, so do it again
} else {
res[newKey] = value; // it's not an object, so set the property
}
}
return res;
}
I wrote another function with prefix feature. I couldn't run your code but I got the answer.
Thanks
https://github.com/vardars/dotize
var dotize = dotize || {};
dotize.convert = function(jsonobj, prefix) {
var newobj = {};
function recurse(o, p, isArrayItem) {
for (var f in o) {
if (o[f] && typeof o[f] === "object") {
if (Array.isArray(o[f]))
newobj = recurse(o[f], (p ? p + "." : "") + f, true); // array
else {
if (isArrayItem)
newobj = recurse(o[f], (p ? p : "") + "[" + f + "]"); // array item object
else
newobj = recurse(o[f], (p ? p + "." : "") + f); // object
}
} else {
if (isArrayItem)
newobj[p + "[" + f + "]"] = o[f]; // array item primitive
else
newobj[p + "." + f] = o[f]; // primitive
}
}
return newobj;
}
return recurse(jsonobj, prefix);
};
Following what #pimvdb did (a compact and effective solution he submitted), I added a little modification that allows me have a function that can be easily exported:
function changeObjectToDotNotationFormat(inputObject, current, prefinalObject) {
const result = prefinalObject ? prefinalObject : {}; // This allows us to use the most recent result object in the recursive call
for (let key in inputObject) {
let value = inputObject[key];
let newKey = current ? `${current}.${key}` : key;
if (value && typeof value === "object") {
changeObjectToDotNotationFormat(value, newKey, result);
} else {
result[newKey] = value;
}
}
return result;
}
i think this would be more elegant...
const toDotNot = (input, parentKey) => Object.keys(input || {}).reduce((acc, key) => {
const value = input[key];
const outputKey = parentKey ? `${parentKey}.${key}` : `${key}`;
// NOTE: remove `&& (!Array.isArray(value) || value.length)` to exclude empty arrays from the output
if (value && typeof value === 'object' && (!Array.isArray(value) || value.length)) return ({ ...acc, ...toDotNot(value, outputKey) });
return ({ ...acc, [outputKey]: value });
}, {});
const input = {a: {b: 'c', e: {f: ['g', null, {g: 'h'}]}}, d: []};
const output = toDotNot(input);
console.log(output);
results in:
// output:
{
"a.b": "c",
"a.e.f.0": "g",
"a.e.f.1": null,
"a.e.f.2.g": "h",
"d": []
}
There are already lots of answers here, but for Typescript this solution works pretty well for me and is typed:
type EncapsulatedStringObject = Record<string, string | object>;
export function convertKeysToDotNotation( object: EncapsulatedStringObject, prefix: string = '' ): Record<string, string> {
const result: Record<string, string> = {};
Object.keys( object ).forEach( key => {
const newPrefix = prefix ? `${prefix}.${key}` : key;
const value = object[ key ];
if ( typeof value === 'object' ) {
Object.assign( result, convertKeysToDotNotation( object[ key ] as EncapsulatedStringObject, newPrefix ) );
} else {
result[ newPrefix ] = value;
}
} );
return result;
}

How can I find key in JavaScript Object when his depth is unknown?

If I have an javascript object like this: {a : { b: { c: { ... }}}}, how can I find if there is an 'x' key in the object and what it's value ?
So long as their is no fear of cyclic references you could do the following
function findX(obj) {
var val = obj['x'];
if (val !== undefined) {
return val;
}
for (var name in obj) {
var result = findX(obj[name]);
if (result !== undefined) {
return result;
}
}
return undefined;
}
Note: This will search for the property 'x' directly in this object or it's prototype chain. If you specifically want to limit the search to this object you can do so doing the following
if (obj.hasOwnProperty('x')) {
return obj['x'];
}
And repeating for pattern for the recursive calls to findX
function hasKey(obj,key){
if(key in obj)
return true;
for(var i in obj)
if(hasKey(obj[i],key))
return true;
return false;
}
ex:
alert(hasKey({a:{b:{c:{d:{e:{f:{g:{h:{i:{}}}}}}}}}},'i'));

Categories