How to apply custom formatting for a JSON stringify? - javascript

I have the following code:
const sample = [
{
name: "apple",
points: [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 }, { x: 7, y: 8 } ],
age: 24
},
{
name: "banana",
points: [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 }, { x: 7, y: 8 } ],
age: 45
}
];
const qwer = JSON.stringify(sample, null, 2);
console.log(qwer);
If you run it, you'll notice it has nice formatting, except for the points array, which is extremely verbose.
I would like everything to be indented like normally (which is why I'm passing in 2 for the final parameter to stringify), but I would like the points array to only take a single line, like how it is declared in the code.
The reason for this is because currently each points array is stretched to like 18 lines, when there will only ever be 3 or 4 items. I would like them to stay on one line.
I tried to use a custom replacer, and while it somewhat worked, it forced the JSON array to be a string. But it's not a string. I want it to stay an array.
Is there any way to do this?

For the general solution, a mini parser would be the best approach, but a quick but ugly-looking approach would be to use a replacer to replace arrays with stringified strings with a unique value as a prefix which can be replaced afterwards.
const sample = [
{
name: "apple",
age: 24,
points: [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 }, { x: 7, y: 8 } ],
},
{
name: "banana",
age: 45,
points: [ { x: 1, y: 2 }, { x: 3, y: 4 }, { x: 5, y: 6 }, { x: 7, y: 8 } ],
}
];
const withNestedStringifiedArrays = JSON.stringify(
sample,
(key, value) => key && Array.isArray(value) ? '##UNIQUE##' + JSON.stringify(value) : value,
2
);
const output = withNestedStringifiedArrays.replace(
/"##UNIQUE##(.*?)"(,)?$/gm,
(_, stringifiedArr, possibleComma = '') => stringifiedArr.replaceAll('\\', '') + possibleComma
);
console.log(output);

Related

Foreach Array Element Search for values in multidimension Array javascript

Trying to match each element of an array to a set of coordinates in a multidimensions array in the following manner:
array1= [0, 5, 4]
array2 = [
{x: 1, y: 4, name: 'A', w: 0},
{x: 2, y: 8, name: 'E', w: 4},
{x: 3, y: 1, name: 'F', w: 5}];
I am hoping to match each element of array 1 to the value of w in array 2
0 -> {x: 1, y: 4, name: 'A', w: 0}
5 -> {x: 3, y: 1, name: 'F', w: 5}
4 -> {x: 2, y: 8, name: 'E', w: 4}
I want to return :
[
{x:1, y,4}, {x:3, y:1},
{x:3, y:1}, {x:2, y:8},
...
];
You should return the required x and y coordinates as an array.
Please find a working fiddle for that.
const array1 = [0, 5, 4]
const array2 = [
{ x: 1, y: 4, name: 'A', w: 0 },
{ x: 2, y: 8, name: 'E', w: 4 },
{ x: 3, y: 1, name: 'F', w: 5 },
];
const tempArray = array1.map((item) => array2.find((node) => node.w === item));
// console.log(tempArray);
const finalArray = tempArray.map((currentNode, index, actualArray) => {
const nextIndex = index === actualArray.length - 1 ? 0 : index + 1;
return [
{ x: currentNode.x, y: currentNode.y },
{ x: actualArray[nextIndex].x, y: actualArray[nextIndex].y },
];
});
console.log(finalArray);
You can chain array filter and map to do something like this
Array.prototype.filter() to filter all elements based on the index from first array and
Array.prototype.map() to modify the object so as to only show the x and y co-ordinates
const array1 = [0, 5, 4];
const array2 = [
{ x: 1, y: 4, name: "A", index: 0 },
{ x: 2, y: 8, name: "E", index: 4 },
{ x: 3, y: 1, name: "F", index: 5 },
];
const newArr = array2.filter(x => array1.includes(x.index)).map(x => ({ x: x.x, y: x.y }));
console.log(newArr)

Flatten nested JavaScript object

I have a nested object and I want to flatten/map it into a single-layered, table-like object.
[{
a: 1,
b: 2,
c: [{
x: 10,
y: 20
}, {
x: 30,
y: 40
}]
}, {
a: 3,
b: 4,
c: [{
x: 50,
y: 60
}, {
x: 70,
y: 80
}]
}]
From that, I want to get something like this:
[{
a: 1,
b: 2,
x: 10,
y: 20
}, {
a: 1,
b: 2,
x: 30,
y: 40
}, {
a: 3,
b: 4,
x: 50,
y: 60
}, {
a: 3,
b: 4,
x: 70,
y: 80
}]
Sure, I could simply iterate over the object with two for loops and put the result info a separate array, but I wonder, if there is a simpler solution. I already tried to play around with flatMap. It works, if I only want the c portion of my nested object, but I don't know how to map a and b to this object.
As some of you asked for some working code, this should do it (untested):
let result = [];
for (const outer of myObj)
for (const inner of outer.c)
result.push({a: outer.a, b: outer.b, x: inner.x, y: inner.y});
The question is, if there is a functional one-liner or even another, better approach. In reality, my object consists of four layers and the nested for loops become messy quite fast.
You may use flatMap method alongwith map on property 'c':
var input = [{ a: 1, b: 2, c: [{ x: 10, y: 20 }, { x: 30, y: 40 }] }, { a: 3, b: 4, c: [{ x: 50, y: 60 }, { x: 70, y: 80 }] }];
const output = input.flatMap(obj =>
obj.c.map(arr => ({a: obj.a, b: obj.b, x: arr.x, y: arr.y}))
);
console.log(output);
Ideally a solution would require something to tell how far down to start classing the object as been a full object, a simple solution is just to pass the level you want. If you don't want to pass the level, you could do a check and if none of the properties have array's, then you would class this as a complete record, but of course that logic is something you would need to confirm.
If you want a generic version that works with multiple levels were you pass the level & using recursion you could do something like this ->
const a=[{a:1,b:2,c:[{x:10,y:20},{x:30,y:40}]},{a:3,b:4,c:[{x:50,y:60},{x:70,y:80}]}];
function flattern(a, lvl) {
const r = [];
function flat(a, l, o) {
for (const aa of a) {
o = {...o};
for (const [k, v] of Object.entries(aa)) {
if (Array.isArray(v) && l < lvl) flat(v, l + 1, o);
else o[k] = v;
}
if (l === lvl) r.push(o);
}
}
flat(a, 1);
return r;
}
console.log(flattern(a, 2));
//console.log(flattern(a, 1));
A flatMap solution would look like this:
const result = myObj.flatMap(outer =>
outer.c.map(inner =>
({a: outer.a, b: outer.b, x: inner.x, y: inner.y})
)
);
Of course, if your object has multiple layers, not just two, and possibly even multiple or unknown properties that have such a nesting, you should try to implement a recursive solution. Or an iterative one, where you loop over an array of property names (for your example case, ["c"]) and apply the flattening level by level.
One of the solution using reduce is:
const list = [{
a: 1,
b: 2,
c: [{
x: 10,
y: 20
}, {
x: 30,
y: 40
}]
}, {
a: 3,
b: 4,
c: [{
x: 50,
y: 60
}, {
x: 70,
y: 80
}]
}]
const flatten = (arr) => {
return arr.reduce((flattened, item) => {
return [
...flattened,
...item.c.reduce((flattenedItem, i) => {
return [
...flattenedItem,
{
a: item.a,
b: item.b,
x: i.x,
y: i.y
}
]
}, [])
]
}, [])
}
console.log(flatten(list));
Using two reducers to flatten your structure
const input = [{
a: 1,
b: 2,
c: [{
x: 10,
y: 20
}, {
x: 30,
y: 40
}]
}, {
a: 3,
b: 4,
c: [{
x: 50,
y: 60
}, {
x: 70,
y: 80
}]
}]
const result = input.reduce((acc_0, x) => {
return [...acc_0, ...x.c.reduce((acc_1, y) => {
const obj = {
a: x.a,
b: x.b,
x: y.x,
y: y.y
}
acc_1.push(obj);
return acc_1;
}, [])]
}, []);
console.log(result)

Find object in array with next lower value

I need to get the next lower object in an array using a weight value.
const data = [
{ weight: 1, size: 2.5 },
{ weight: 2, size: 3.0 },
{ weight: 4, size: 3.5 },
{ weight: 10, size: 4.0 },
{ weight: 20, size: 5.0 },
{ weight: 30, size: 6.0 }
]
If the weight is 19, I need to get the object { weight: 10, size: 4.0 }.
With this attempt, I do get the closest object, but I always need to get the object with the next lowest value. If weight is smaller then 1, the first element should be returned.
const get_size = (data, to_find) =>
data.reduce(({weight}, {weight:w}) =>
Math.abs(to_find - w) < Math.abs(to_find - weight) ? {weight: w} : {weight}
)
If the objects' weights are in order, like in the question, one option is to iterate from the end of the array instead. The first object that matches will be what you want.
If the .find below doesn't return anything, alternate with || data[0] to get the first item in the array:
const data = [
{ weight: 1, size: 2.5 },
{ weight: 2, size: 3.0 },
{ weight: 4, size: 3.5 },
{ weight: 10, size: 4.0 },
{ weight: 20, size: 5.0 },
{ weight: 30, size: 6.0 }
]
const output = data.reverse().find(({ weight }) => weight < 19) || data[0];
console.log(output);
(if you don't want to mutate data, you can .slice it first)

Summarize the frequency of array of objects

Assume I have the following array of objects.
data = [
{ x: 1, y: 1 },
{ x: 2, y: 2 },
{ x: 3, y: 3 },
{ x: 2, y: 2 },
{ x: 1, y: 1 },
{ x: 1, y: 2 },
{ x: 1, y: 1 }
]
what I need is to summarize the frequency of identical object in the array. The output will look like:
summary = [
{ x: 1, y: 1, f: 3 },
{ x: 1, y: 2, f: 1 },
{ x: 2, y: 2, f: 2 },
{ x: 3, y: 3, f: 1 }
]
For now I have this code
const summary = data.map((item, index, array) => {
return { x: item.x, y: item.y, f: array.filter(i => i === item).length };
});
But I suppose I can do better by using reduce or includes. Any ideas?
Reduce into an object whose keys uniquely represent an object, whose values are the object (with x, y, and f properties). On each iteration, increment the appropriate key's f property, or create the key on the accumulator if it doesn't exist yet:
const data = [
{ x: 1, y: 1 },
{ x: 2, y: 2 },
{ x: 3, y: 3 },
{ x: 2, y: 2 },
{ x: 1, y: 1 },
{ x: 1, y: 2 },
{ x: 1, y: 1 }
];
const countObj = data.reduce((a, obj) => {
const objString = obj.x + '_' + obj.y;
if (!a[objString]) {
a[objString] = { ...obj, f: 1 };
} else {
a[objString].f++;
}
return a;
}, {});
const output = Object.values(countObj);
console.log(output);
Don't use map - you're better off using reduce like so:
const summary = Object.values(data.reduce((a, { x, y }) => {
a[`${x}-${y}`] = a[`${x}-${y}`] || { x, y, f: 0 };
a[`${x}-${y}`].f++;
return a;
}, {}));
Object.values(data.reduce((sum, i) => {
i_str = JSON.stringify(i); // objects can't be keys
sum[i_str] = Object.assign({}, i, {f: sum[i_str] ? sum[i_str].f+1 : 1});
return sum;
}, {}));
Note:
This snippet will work on an array of any arbitrary objects, as long as they are stringifiable.
Results are not ordered, since object keys aren’t ordered. If this is an issue, sort at will.
What you’re doing, is counting the times an object exists in an array. You probably want results external to the objects, as opposed to embedded in them. Something along these lines might be more manageable, returning a mapping of descriptions of the objects to a count:
data.reduce((sum, i) => {
i_str = JSON.stringify(i); // objects can't be keys
sum[i_str] = sum[i_str] ? sum[i_str]+1 : 1;
return sum;
}, {});
A simple solution based on Array#reduce would be as detailed below:
const data = [
{ x: 1, y: 1 },
{ x: 2, y: 2 },
{ x: 3, y: 3 },
{ x: 2, y: 2 },
{ x: 1, y: 1 },
{ x: 1, y: 2 },
{ x: 1, y: 1 }
];
const summary = data.reduce((frequencySummary, item) => {
/* Find a match for current item in current list of frequency summaries */
const itemMatch = frequencySummary.find(i => i.x === item.x && i.y === item.y)
if(!itemMatch) {
/* If no match found, add a new item with inital frequency of 1 to the result */
frequencySummary.push({ ...item, f : 1 });
}
else {
/* If match found, increment the frequency count of that match */
itemMatch.f ++;
}
return frequencySummary;
}, []);
console.log(summary)
I know using reduce is probably better, but I tend to use forEach and findIndex for better readability.
var data = [
{ x: 1, y: 1 },
{ x: 2, y: 2 },
{ x: 3, y: 3 },
{ x: 2, y: 2 },
{ x: 1, y: 1 },
{ x: 1, y: 2 },
{ x: 1, y: 1 }
];
var summary = [];
data.forEach(function(d){
var idx = summary.findIndex(function(i){
return i.x === d.x && i.y === d.y;
});
if(idx < 0){
var sum = Object.assign({}, d);
sum.f = 1;
summary.push(sum);
} else {
summary[idx].f = summary[idx].f + 1;
}
});
console.log(summary);
Create nested objects. The outer object uses x values as keys, the nested object contains y values as keys, and the values are the frequencies.
data = [
{ x: 1, y: 1 },
{ x: 2, y: 2 },
{ x: 3, y: 3 },
{ x: 2, y: 2 },
{ x: 1, y: 1 },
{ x: 1, y: 2 },
{ x: 1, y: 1 }
];
const nested = data.reduce((a, {x, y}) => {
a[x] = a[x] || {};
a[x][y] = a[x][y] ? a[x][y] + 1 : 1
return a;
}, {});
const summary = [];
Object.keys(nested).forEach(x => Object.keys(nested[x]).forEach(y => summary.push({x, y, f: nested[x][y]})));
console.log(summary);
You can use reduce and Map, club the use x and y as key, on every iteration check if the same key is already present on Map than just increase f count by 1 if not than set it to 1
const data = [{ x: 1, y: 1 },{ x: 2, y: 2 },{ x: 3, y: 3 },{ x: 2, y: 2 },{ x: 1, y: 1 },{ x: 1, y: 2 },{ x: 1, y: 1 }];
const countObj = data.reduce((a, obj) => {
const objString = obj.x + '_' + obj.y;
let value = a.get(objString) || obj
let f = value && value.f || 0
a.set(objString, { ...value, f: f+1 })
return a;
}, new Map());
console.log([...countObj.values()]);

Get only 1 object from array with 2 similar objects

As you can see here I have an array of 2 objects which have the same name and other elements, instead of x,y. I'm trying to console log them, and it works just fine, am getting 2 objects. My question is, how do I console.log only one of them, the first one?
var _hero = [{
nick: "Mike",
lvl: 500,
x: 10,
y: 10
}, {
nick: "Mike",
lvl: 500,
x: 15,
y: 15
}]
let main = () => {
_hero.forEach(function(_hero) {
if (_hero.nick == "Mike") {
console.log(_hero);
}
});
};
main();
Use array.find that will give you only the first matching element
var _hero = [{
nick: "Mike",
lvl: 500,
x: 10,
y: 10
}, {
nick: "Mike",
lvl: 500,
x: 15,
y: 15
}]
console.log(_hero.find(data=>data.nick ==='Mike'));
Use second parameter in forEach(function(hero, i){... to check the iteration like the following:
var _hero = [{
nick: "Mike",
lvl: 500,
x: 10,
y: 10
}, {
nick: "Mike",
lvl: 500,
x: 15,
y: 15
}]
let main = () => {
_hero.forEach(function(_hero,i) {
if (_hero.nick == "Mike" && i == 0) {
console.log(_hero);
}
});
};
main();

Categories