Spread operator with reduce function in js - javascript

I trying to generate all possible paths of the given json object. Some how I generated the paths but I want my final array in a flatten manner (no nested arrays inside the final array).
I tried speading the array, but the final array contains some nested arrays. I want to have all the elements in a flatter manner.
Current op:
[
"obj",
"level1.level2.level3.key",
[
"arrayObj.one[0].name",
"arrayObj.one[0].point"
]
]
Expected:
[
"obj",
"level1.level2.level3.key",
"arrayObj.one[0].name",
"arrayObj.one[0].point"
]
Below I have attached the snippet I tried.
const allPaths = (obj, path = "") =>
Object.keys(obj).reduce((res, el) => {
if (Array.isArray(obj[el]) && obj[el].length) {
return [...res, ...obj[el].map((item, index) => {
return [...res, ...allPaths(item, `${path}${el}[${index}].`)];
})];
} else if (typeof obj[el] === "object" && obj[el] !== null) {
return [...res, ...allPaths(obj[el], `${path}${el}.`)];
}
return [...res, path + el];
}, []);
const obj = {
obj: 'sample',
level1: {
level2: {
level3: {
key: 'value'
}
}
},
arrayObj: {
one: [{
name: 'name',
point: 'point'
},
{
name: 'name2',
point: 'point2'
},
{
name: 'name2',
point: 'point2'
}
]
}
}
console.log(allPaths(obj));

UPDATE: I didn't understood the question previously correctly. Now i do. So yes the below code will solve the problem for you.
You want your object to be flattened with dots
If thats the case the below should work
const obj = {
obj: 'sample',
level1: {
level2: {
level3: {
key: 'value'
}
}
},
arrayObj: {
one: [{
name: 'name',
point: 'point'
},
{
name: 'name2',
point: 'point2'
},
{
name: 'name2',
point: 'point2'
}
]
}
}
function flatten(data, prefix) {
let result = {}
for(let d in data) {
if(typeof data[d] == 'object') Object.assign(result, flatten(data[d], prefix + '.' + d))
else result[(prefix + '.' + d).replace(/^\./, '')] = data[d]
}
return result
}
console.log(flatten(obj, ''))

Related

ES5 JavaScript: Find specific property in nested objects and return its value

I need to return the value of a specific property of nested objects with ES5 syntax. Every object can have its own structure, so the needed property can be on different levels/places. E.g. -> I have three different objects and the value of property "source" is needed:
first_data has that property in list.details.source
second_data has that property in list.details.products[0]._new.source
third_data does not have this property, therefore it should return false
So how can I return the value of the specific property with consideration, that it can be on any position in object?
var first_data = {
area: "South",
code: "S265",
info: {
category: "enhanced",
label: "AB | 27AS53",
variable: "VR"
},
list: {
area: "Mid",
details: [
{
source: "Spain",
totals: 12,
products: [
{
name: "ABC",
brand: "Nobrand",
id: "111",
category: "Men",
}
]
}
]
},
time: 1654775446138
};
var second_data = {
area: "South",
code: "S265",
info: {
category: "enhanced",
label: "AB | 27AS53",
variable: "VR"
},
list: {
area: "Mid",
details: [
{
products: [
{
name: "ABC",
brand: "Nobrand",
id: "111",
category: "Men",
_new: {
source: "Spain",
totals: 12
}
}
]
}
]
},
time: 1654775446138
};
var third_data = {
area: "South",
code: "S265",
info: {
category: "enhanced",
label: "AB | 27AS53",
variable: "VR"
},
list: {
area: "Mid",
details: [
{
products: [
{
name: "ABC",
brand: "Nobrand",
id: "111",
category: "Men"
}
]
}
]
},
time: 1654775446138
};
I first tried to solve it with ES6, so that I can rewrite it in a second step into ES5. Here is what I have so far. The first problem is that here I am getting a false, but the property exists.
var propertyExists = function (obj, key) {
if(obj === null || obj === undefined) {
return false;
}
for(const k of Object.keys(obj)) {
if(k === key) {
return obj[k]
}
else {
const val = obj[k];
if(typeof val === 'object') {
if(propertyExists(val, key) === true) {
return true;
}
}
}
}
return false;
}
propertyExists(first_data, 'source')
Your propertyExists function didn't work because it returned the value of source but it later checked if the value is equal to true (as described by Felix Kling in a comment above).
Here's my implementation (originally in ES6 but I used a typescript compiler with target set to ES5):
var findProp = function (obj, prop) {
if (typeof obj != "object") {
return false;
}
if (obj.hasOwnProperty(prop)) {
return obj[prop];
}
for (var _i = 0, _a = Object.keys(obj); _i < _a.length; _i++) {
var p = _a[_i];
if (typeof obj[p] === "object") {
var t = findProp(obj[p], prop);
if (t) {
return t;
}
}
}
return false;
};
Note: It might be faster to detect which object structure it is and retrieve the value because you would then know where it is.

Modifying a specific value in a nested object (JavaScript)

I got this type of object:
const obj = {
group: {
data: {
data: [
{
id: null,
value: 'someValue',
data: 'someData'
}
]
}
}
};
I need to edit this object so whenever null is in the property value,
it would be replaced with some string.
Meaning if the replacement string will be 'someId',
the expected outcome is:
const obj = {
group: {
data: {
data: [
{
id: 'someId',
value: 'someValue',
data: 'someData'
}
]
}
}
};
Closest I found were this and this but didn't manage to manipulate the solutions there to what i need.
How should I do it?
Probably running into issues with the array values. Pass in the index of the array to modify. In this case [0]
obj.group.data.data[0].id = "someId"
EDIT
This will update all null values of id inside the data array:
obj.group.data.data.forEach(o => {
if (o.id === null) {
o.id = "someId"
}
})
Another EDIT
Here is an algorithm to recursively check all deeply nested values in an object. It will compile an array of object paths where null values live. There is an included helper method to find and update the value of the object at the given path in the array. There is a demonstration of the program in the console.
const object = {
group: {
data: {
data: [
{
id: null,
value: "foo",
data: [null, "bar", [null, { stuff: null }]]
},
{
id: null,
value: null,
data: {
bar: [null]
}
},
{
id: null,
value: "foo",
data: null
},
{
id: 4,
value: "foo",
data: "bar"
},
{
id: 4,
value: "stuff",
data: null
}
]
},
attributes: null,
errors: ["stuff", null]
}
}
const inspectProperty = (key, obj, path = "") => {
if (typeof obj[key] === "object") {
if (obj[key] instanceof Array) {
return analyzeArray(obj[key], `${path ? path + "." : ""}${key}`);
}
return analyzeObj(obj[key], `${path ? path + "." : ""}${key}`);
}
return [];
};
const analyzeKey = (obj, key, path = "") => {
if (obj[key] === null) return [`${path ? path + "." : ""}${key}`];
return inspectProperty(key, obj, path).reduce((a, k) => [...a, ...k], []);
};
const analyzeObj = (obj, path = "") => {
return Object.keys(obj).map((item) => analyzeKey(obj, item, path));
};
const analyzeArray = (array, path) => {
return array.map((item, i) => analyzeKey(array, i, path));
};
const updateNullValue = (path, value) => {
let p = path.split(".");
p.reduce((accum, iter, i) => {
if (i === p.length - 1) {
accum[iter] = value;
return object;
}
return accum[iter];
}, object);
};
let nullValues = analyzeObj(object)[0]
console.log(nullValues)
nullValues.forEach((nullVal, i) => {
updateNullValue(nullVal, "hello-" + i)
})
console.log(object)

Convert object to array of prorperties

I need to convert object:
{
middleName: null,
name: "Test Name",
university: {
country: {
code: "PL"
},
isGraduated: true,
speciality: "Computer Science"
}
}
to array:
[{
key: "name",
propertyValue: "Test Name",
},
{
key: "middleName",
propertyValue: null,
},
{
key: "university.isGraduated",
propertyValue: true,
},
{
key: "university.speciality",
propertyValue: "Computer Science",
},
{
key: "university.country.code",
propertyValue: "PL"
}];
I wrote algorithm, but it's pretty dummy, how can I improve it? Important, if object has nested object than I need to write nested object via dot (e.g university.contry: "value")
let arr = [];
Object.keys(parsedObj).map((key) => {
if (parsedObj[key] instanceof Object) {
Object.keys(parsedObj[key]).map((keyNested) => {
if (parsedObj[key][keyNested] instanceof Object) {
Object.keys(parsedObj[key][keyNested]).map((keyNestedNested) => {
arr.push({ 'key': key + '.' + keyNested + '.' + keyNestedNested, 'propertyValue': parsedObj[key][keyNested][keyNestedNested] })
})
} else {
arr.push({ 'key': key + '.' + keyNested, 'propertyValue': parsedObj[key][keyNested] })
}
})
} else {
arr.push({ 'key': key, 'propertyValue': parsedObj[key] })
}
});
Thanks
A recursive function implementation.
I have considered that your object consist of only string and object as the values. If you have more kind of data types as your values, you may have to develop on top of this function.
const myObj = {
middleName: null,
name: "Test Name",
university: {
country: {
code: "PL"
},
isGraduated: true,
speciality: "Computer Science"
}
}
const myArr = [];
function convertObjectToArray(obj, keyPrepender) {
Object.entries(obj).forEach(([key, propertyValue]) => {
if (typeof propertyValue === "object" && propertyValue) {
const updatedKey = keyPrepender ? `${keyPrepender}.${key}` : key;
convertObjectToArray(propertyValue, updatedKey)
} else {
myArr.push({
key: keyPrepender ? `${keyPrepender}.${key}` : key,
propertyValue
})
}
})
}
convertObjectToArray(myObj);
console.log(myArr);
I'd probably take a recursive approach, and I'd probably avoid unnecessary intermediary arrays (though unless the original object is massive, it doesn't matter). For instance (see comments):
function convert(obj, target = [], prefix = "") {
// Loop through the object keys
for (const key in obj) {
// Only handle "own" properties
if (Object.hasOwn(obj, key)) {
const value = obj[key];
// Get the full key for this property, including prefix
const fullKey = prefix ? prefix + "." + key : key;
if (value && typeof value === "object") {
// It's an object...
if (Array.isArray(value)) {
throw new Error(`Arrays are not valid`);
} else {
// ...recurse, providing the key as the prefix
convert(value, target, fullKey);
}
} else {
// Not an object, push it to the array
target.push({key: fullKey, propertyValue: value});
}
}
}
// Return the result
return target;
}
Live Example:
const original = {
middleName: null,
name: "Test Name",
university: {
country: {
code: "PL"
},
isGraduated: true,
speciality: "Computer Science"
}
};
function convert(obj, target = [], prefix = "") {
// Loop through the object keys
for (const key in obj) {
// Only handle "own" properties
if (Object.hasOwn(obj, key)) {
const value = obj[key];
// Get the full key for this property, including prefix
const fullKey = prefix ? prefix + "." + key : key;
if (value && typeof value === "object") {
// It's an object...
if (Array.isArray(value)) {
throw new Error(`Arrays are not valid`);
} else {
// ...recurse, providing the key as the prefix
convert(value, target, fullKey);
}
} else {
// Not an object, push it to the array
target.push({key: fullKey, propertyValue: value});
}
}
}
// Return the result
return target;
}
const result = convert(original, []);
console.log(result);
.as-console-wrapper {
max-height: 100% !important;
}
Note that I've assumed the order of the array entries isn't significant. The output you said you wanted is at odds with the standard order of JavaScript object properties (yes, they have an order now; no, it's not something I suggest relying on 😀). I've gone ahead and not worried about the order within an object.
This is the most bulletproof I could do :D, without needing a global variable, you just take it, and us it wherever you want!
const test = {
middleName: null,
name: "Test Name",
university: {
country: {
code: "PL"
},
isGraduated: true,
speciality: "Computer Science"
}
};
function toPropertiesByPath(inputObj) {
let arr = [];
let initialObj = {};
const getKeys = (obj, parentK='') => {
initialObj = arr.length === 0 ? obj: initialObj;
const entries = Object.entries(obj);
for(let i=0; i<entries.length; i++) {
const key = entries[i][0];
const val = entries[i][1];
const isRootElement = initialObj.hasOwnProperty(key);
parentK = isRootElement ? key: parentK+'.'+key;
if(typeof val === 'object' && val!==null && !Array.isArray(val)){
getKeys(val, parentK);
} else {
arr.push({ key: parentK, property: val });
}
}
};
getKeys(inputObj);
return arr;
}
console.log(toPropertiesByPath(test));
I wrote a small version using recursive function and another for validation is an object.
let values = {
middleName: null,
name: "Test Name",
university: {
country: {
code: "PL"
},
isGraduated: true,
speciality: "Computer Science"
}
}
function isObject(obj) {
return obj != null && obj.constructor.name === "Object"
}
function getValues(values) {
let arrValues = Object.keys(values).map(
v => {
return { key: v, value: isObject(values[v]) ? getValues(values[v]) : values[v] };
});
console.log(arrValues);
}
getValues(values);

Find element in map

I have a map of objects:
"0": {
key: 'id',
value: {
name: "eval"
// other variables
}
},
"1": {
key: 'id',
value: {
name: "help"
// other variables
}
} // and so on
I need to find an element in map that's name variable is eqaul to "eval". What's the easiest way to do this?
If "map" is an array
let arr = [{key:'id', value:{ name:'eval' }}]
let item = arr.find(el => el.value.name == 'eval')
If "map" is an object
let obj = {0:{key:'id', value:{ name:'eval' }}}
let item = Object.values(obj).find(el => el.value.name == 'eval')
Use <Array>.from to convert map values to array and after filter what you want.
const map = new Map();
map.set(0, {
key: 'id',
value: {
name: "eval"
}
});
map.set(1, {
key: 'id',
value: {
name: "help"
}
});
const result = Array.from(map.values())
.filter(x => x.value.name === 'eval')[0];
console.log(result);
The good old forEach Loop can do it too.
const data = [{
key: 'id',
value: {
name: "eval"
// other variables
}
},
{
key: 'id',
value: {
name: "help"
// other variables
}
}]
let res = [];
data.forEach((el) => {
if (el.value.name === "eval") {
res.push(el);
}
})
console.log(res)
You can do this
const tmp = {
"0": {
key: "id",
value: {
name: "eval"
// other variables
}
},
"1": {
key: "id",
value: {
name: "eval"
// other variables
}
}
};
function findEval(obj, target) {
const elem = Object.keys(obj).filter(key => tmp[key].value.name === target);
return elem.map(e => obj[e]);
}
console.log(findEval(tmp, 'eval'))
but better use lodash Find property by name in a deep object
simple and best solution
const tmp = {
"0": {
key: "id",
value: {
name: "eval"
// other variables
}
},
"1": {
key: "id",
value: {
name: "eval"
// other variables
}
}
};
function findEval(obj, target) {
for (var i=0; i < Object.keys(obj).length; i++) {
if (obj[i].value.name === target) {
return obj[i].value.name;
}
}
}
console.log(findEval(tmp, 'eval'))

Recursively collect values for property using lodash

For a nested complex object or array, I would like to collect all values for a given property name. Example:
var structure = {
name: 'alpha',
array: [
{ name: 'beta' },
{ name: 'gamma' }
],
object: {
name: 'delta',
array: [
{ name: 'epsilon' }
]
}
};
// expected result: [ 'alpha', 'beta', 'gamma', 'delta', 'epsilon' ]
It's obvious how to achieve this using plain JS, but: Is there any elegant, concise approach using lodash?
[edit] Current variant below. Nicer solutions welcome!
function getPropertyRecursive(obj, property) {
var values = [];
_.each(obj, function(value, key) {
if (key === property) {
values.push(value);
} else if (_.isObject(value)) {
values = values.concat(getPropertyRecursive(value, property));
}
});
return values;
}
This can be done elegantly with the following mixin, which is a recursive version of _.toPairs:
_.mixin({
toPairsDeep: obj => _.flatMap(
_.toPairs(obj), ([k, v]) =>
_.isObjectLike(v) ? _.toPairsDeep(v) : [[k, v]])
});
then to get the result you want:
result = _(structure)
.toPairsDeep()
.map(1)
.value()
If there are scalar properties other than name, you'll have to filter them out:
result = _(structure)
.toPairsDeep()
.filter(([k, v]) => k === 'name')
.map(1)
.value()
There's no Lodash/Underscore function that I know if that will do what you're looking for.
So what are you looking to do? Well, specifically you're looking to extract the values of all of the name properties out of a aggregate structure. How would we generalize that? In other words, if you were looking to add such functionality to Lodash/Underscore, how would you reframe the problem? After all, most people don't want to get the values of the name properties. You could create a generic function where you supply the name of the property you want, but...thinking even more abstractly than that, what you really want to do is visit all of the nodes in a aggregate structure and do something with them. If we consider aggregate structures in JavaScript as generic trees, we can take a recursive approach using a depth-first walk:
function walk(o, f) {
f(o);
if(typeof o !== 'object') return;
if(Array.isArray(o))
return o.forEach(e => walk(e, f));
for(let prop in o) walk(o[prop], f);
}
Now we can do what you're looking for by walking the structure and adding things to an array:
const arr = [];
walk(structure, x => if(x !== undefined && x.name) arr.push(x.name));
This isn't quite functional enough for my tastes, though...there's a side effect on arr here. So an even better generic approach (IMO) would be to allow a context object to ride along (or an accumulator if you will, a la Array#reduce):
function walk(o, f, context) {
f(o, context);
if(typeof o !== 'object') return context;
if(Array.isArray(o)) return o.forEach(e => walk(e, f, context)), context;
for(let prop in o) walk(o[prop], f, context);
return context;
}
Now you can call it like this, side-effect free:
const arr = walk(structure, (x, context) => {
if(x !== undefined && x.name) context.push(x.name);
}, []);
Iterate the object recursively using _.reduce():
function getPropertyRecursive(obj, prop) {
return _.reduce(obj, function(result, value, key) {
if (key === prop) {
result.push(value);
} else if (_.isObjectLike(value)) {
return result.concat(getPropertyRecursive(value, prop));
}
return result;
}, []);
}
var structure = {
name: 'alpha',
array: [{
name: 'beta'
}, {
name: 'gamma'
}],
object: {
name: 'delta',
array: [{
name: 'epsilon'
}]
}
};
var result = getPropertyRecursive(structure, 'name');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.2/lodash.min.js"></script>
You could iterate the object and call it again for arrays or objects. Then get the wanted property.
'use strict';
function getProperty(object, key) {
function iter(a) {
var item = this ? this[a] : a;
if (this && a === key) {
return result.push(item);
}
if (Array.isArray(item)) {
return item.forEach(iter);
}
if (item !== null && typeof item === 'object') {
return Object.keys(item).forEach(iter, item);
}
}
var result = [];
Object.keys(object).forEach(iter, object);
return result;
}
var structure = { name: 'alpha', array: [{ name: 'beta' }, { name: 'gamma' }], object: { name: 'delta', array: [{ name: 'epsilon' }] } };
console.log(getProperty(structure,'name'));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Based on the answer ( https://stackoverflow.com/a/39822193/3443096 ) , here's another idea for mixin:
_.mixin({
extractLeaves: (obj, filter, subnode, subpathKey, rootPath, pathSeparator) => {
var filterKv = _(filter).toPairs().flatMap().value()
var arr = _.isArray(obj) ? obj : [obj]
return _.flatMap(arr, (v, k) => {
if (v[filterKv[0]] === filterKv[1]) {
var vClone = _.clone(v)
delete vClone[subnode]
vClone._absolutePath = rootPath + pathSeparator + vClone[subpathKey]
return vClone
} else {
var newRootPath = rootPath
if (_.isArray(obj)) {
newRootPath = rootPath + pathSeparator + v[subpathKey]
}
return _.extractLeaves(
v[subnode], filter, subnode,
subpathKey, newRootPath, pathSeparator
)
}
})
}
});
This work for this example JSON, where you want to extract leaf-nodes:
{
"name": "raka",
"type": "dir",
"children": [{
"name": "riki",
"type": "dir",
"children": [{
"name": "roko",
"type": "file"
}]
}]
}
Use it this way:
_.extractLeaves(result, {type: "file"}, "children", "name", "/myHome/raka", "/")
And you will get:
[
{
"name": "roko",
"type": "file",
"_absolutePath": "/myHome/raka/riki/roko"
}
]

Categories