Reduce json api document to camel case - javascript

I would like to reduce a json api standard document to a camel version. I was able to make a camelCase objects and single primitive types keys.
I would like the desired output to be every key to be camelCase. So in the example above first-name would turn into firstName, snake-case would turn into snakeCase. The problem I'm facing is how to approach an array of objects using the same recursive call I'm using right now.
import _ from "lodash";
const data = {
id: 1,
type: "user",
links: { self: "/movies/1" },
meta: { "is-saved": false },
"first-name": "Foo",
"last-name": "Bar",
locations: ["SF"],
actors: [
{ id: 1, type: "actor", name: "John", age: 80 },
{ id: 2, type: "actor", name: "Jenn", age: 40 }
],
awards: [
{
id: 4,
type: "Oscar",
links: ["asd"],
meta: ["bar"],
category: "Best director",
'snake_case': 'key should be snakeCase'
}
],
name: { id: 1, type: "name", title: "Stargate" }
};
const needsCamelCase = str => {
return str.indexOf("-") > -1 || str.indexOf("_") > -1;
};
const strToCamelCase = function(str) {
return str.replace(/^([A-Z])|[\s-_](\w)/g, function(match, p1, p2, offset) {
if (p2) return p2.toUpperCase();
return p1.toLowerCase();
});
};
const toCamelCase = obj => {
Object.keys(obj).forEach(key => {
if (_.isPlainObject(obj[key])) {
return toCamelCase(obj[key]);
}
if (_.isArray(obj[key])) {
// console.log(obj[key]);
obj[key].forEach(element => {
console.log(element);
});
//obj[key].foreach(element_ => toCamelCase);
}
if (needsCamelCase(key)) {
obj[strToCamelCase(key)] = obj[key];
delete obj[key];
}
});
return obj;
};
// toCamelCase(data);
console.log(toCamelCase(data));
Here is a codesand box: https://codesandbox.io/s/javascript-l842u

the logic is quite simple: if it's an object, just call to toCamelCase, if it's an array, iterate over it to create a new array. If it's an array of object, transform it with toCamelCase, if it's an array of something else keep it as is.
The solution would probably look like this:
const _ = require('lodash');
const data = {
id: 1,
type: "user",
links: { self: "/movies/1" },
meta: { "is-saved": false },
"first-name": "Foo",
"last-name": "Bar",
locations: ["SF"],
actors: [
{ id: 1, type: "actor", name: "John", age: 80 },
{ id: 2, type: "actor", name: "Jenn", age: 40 }
],
awards: [
{
id: 4,
type: "Oscar",
links: ["asd"],
meta: ["bar"],
category: "Best director",
'snake_case': 'key should be snakeCase'
}
],
name: { id: 1, type: "name", title: "Stargate" }
};
const needsCamelCase = str => {
return str.indexOf("-") > -1 || str.indexOf("_") > -1;
};
const strToCamelCase = function(str) {
return str.replace(/^([A-Z])|[\s-_](\w)/g, function(match, p1, p2, offset) {
if (p2) return p2.toUpperCase();
return p1.toLowerCase();
});
};
const toCamelCase = obj => {
Object.keys(obj).forEach(key => {
const camelCasedKey = needsCamelCase(key) ? strToCamelCase(key) : key;
const value = obj[key];
delete obj[key];
obj[camelCasedKey] = value;
if (_.isPlainObject(value)) {
obj[camelCasedKey] = toCamelCase(value);
}
if (_.isArray(value)) {
obj[camelCasedKey] = value.map(item => {
if (_.isPlainObject(item)) {
return toCamelCase(item);
} else {
return item;
}
});
}
});
return obj;
};
// toCamelCase(data);
console.log(toCamelCase(data));

Related

How to convert array of objects into enum like key value pair in javascript?

I have an array
const a = [
{ name: "read-web-courses" },
{ name: "example" },
{ name: "t_gql" },
{ name: "ddddd" },
];
I am trying it to reduce it to the below given output , However I am stuck
Output
{0:"read-web-courses",1:"example",2:"t_gql",3:"ddddd"}
You could map the wanted property and assign the pairs to the object.
const
array = [{ name: "read-web-courses" }, { name: "example" }, { name: "t_gql" }, { name: "ddddd" }],
result = Object.assign({}, array.map(({ name }) => name));
console.log(result);
You can use Array.reduce like below.
const a = [
{ name: "read-web-courses" },
{ name: "example" },
{ name: "t_gql" },
{ name: "ddddd" },
];
const convert = arr => (
arr.reduce((total, value, index) => {
total[index] = value.name;
return total;
}, {})
)
console.log(convert(a));
This is accomplished using Array#reduce, where you can use the index from the reduce callback as the key of the new object:
const a = [ { name: "read-web-courses" }, { name: "example" }, { name: "t_gql" }, { name: "ddddd" }];
const res = a.reduce((r, o, i) => {
r[i] = o.name;
return r;
}, {});
console.log(res);
Also one more approach using Object#fromEntries and Array#map, where each object is converted to an array of key, value pairs:
const a = [ { name: "read-web-courses" }, { name: "example" }, { name: "t_gql" }, { name: "ddddd" }];
const res = Object.fromEntries(a.map((o, i) => [i, o.name]));
console.log(res)

Algorithm from folderstring to correct folderstructure in javascript

I have an array of data which is a string of folders:
var data = [{ name: "/X" }, { name: "/X/Y" }, { name: "/X2" }, { name: "/X2/Z" }, { name: "/X/k" }]
For a component to display this items I need them sorted nested like these:
var data = [{ name: "/X", sub: [{ name: "/Y" }, { name: "/k" }]}, { name: "/X2" }, sub: [{ name: "/Z" }] }]
These items are just examples, the item count is 1000+ and the nested items can be unlimited too.
Any ideas how to do that?
You could do this with forEach and reduce methods and use one object to keep track of level based on the current part of the name property value.
const data = [{ name: "/X" }, { name: "/X/Y" }, { name: "/X2" }, { name: "/X2/Z" }, {name: '/X/K/1'}, {name: '/X/K/2'}]
const result = []
const level = {result}
data.forEach(({ name, ...rest }) => {
name.split('/').filter(Boolean).reduce((r, k) => {
if (!r[k]) {
r[k] = { result: [] }
r.result.push({
name: `/${k}`,
sub: r[k].result
})
}
return r[k]
}, level)
})
console.log(result)
Using reduce() and Map()
var data = [{ name: "/X" }, { name: "/X/Y" }, { name: "/X2" }, { name: "/X2/Z" }, { name: "/X/k" }]
var res = data.reduce((a, i) => {
let s = i.name.match(/\/\w+/g) || []
if (a.has(s[0])) {
let path = a.get(s[0])
i.name = s[1]
path.sub = path.sub || []
path.sub.push(i)
} else {
a.set(i.name, i)
}
return a
}, new Map())
console.log([...res.values()])

How to change the nested array object to object depending on type in javascript

I would like to know how to change nested array object to object depending on key in javascript
I have objects obj1 and obj2, depending on key item type change the object.
function changeObj(obj){
let result = obj.reduce(function (acc, item) {
if(item.items.trim() !== "" && item.key.trim() !== ""){
acc[item.key] = item.items
return acc
}
return acc
}, {});
return result;
}
let result = this.changeObj(obj2)
var obj1 = [
{ id:0, items:["SG","AU"], count: 2, key:"countries"},
{ id:1, items:["finance"], count: 3 key:"info"}
]
var obj2 = [
{ id:0, items: "SG", key: "country"},
{ id:1, items: "details", key: "info"}
]
Expected Output:
// if items key is array
{
fields: {
countries: ["SG","AU",2],
info: ["finance",3]
}
}
//if items key is string
{
fields: {
country: "SG",
info: "details"
}
}
I think the reason your code is not running is because the wrong format of your objects (1 and 2). Your code is okay except the condition because trim() only works on string type so it errors on array. Try this code snippet
function changeObj(obj){
let result = obj.reduce(function (acc, item) {
acc[item.key] = item.items;
return acc;
}, {});
return result;
}
var obj1 = [
{ id:0, items:["SG","AU"], count: 2, key:"countries"},
{ id:1, items:["finance"], count: 3, key:"info"}
]
var obj2 = [
{ id:0, items: "SG", key: "country"},
{ id:1, items: "details", key: "info"}
]
console.log(changeObj(obj1));
const changeObj = obj =>
obj.reduce((acc, item) => {
if (Array.isArray(item.items)) {
acc[item.key] = [...item.items, item.count];
} else {
acc[item.key] = item.items;
}
return acc;
}, {});
var obj1 = [
{ id: 0, items: ['SG', 'AU'], count: 2, key: 'countries' },
{ id: 1, items: ['finance'], count: 3, key: 'info' }
];
var obj2 = [
{ id: 0, items: 'SG', key: 'country' },
{ id: 1, items: 'details', key: 'info' }
];
console.log(changeObj(obj1));
console.log(changeObj(obj2));
or cleaned up even more
const changeObj = obj =>
obj.reduce((acc, { items, key, count }) => {
Array.isArray(items) ? (acc[key] = [...items, count]) : (acc[key] = items);
return acc;
}, {});
var obj1 = [
{ id: 0, items: ['SG', 'AU'], count: 2, key: 'countries' },
{ id: 1, items: ['finance'], count: 3, key: 'info' }
];
var obj2 = [
{ id: 0, items: 'SG', key: 'country' },
{ id: 1, items: 'details', key: 'info' }
];
console.log(changeObj(obj1));
console.log(changeObj(obj2));

How to find a object in a nested array using recursion in JS

Consider the following deeply nested array:
const array = [
{
id: 1,
name: "bla",
children: [
{
id: 23,
name: "bla",
children: [{ id: 88, name: "bla" }, { id: 99, name: "bla" }]
},
{ id: 43, name: "bla" },
{
id: 45,
name: "bla",
children: [{ id: 43, name: "bla" }, { id: 46, name: "bla" }]
}
]
},
{
id: 12,
name: "bla",
children: [
{
id: 232,
name: "bla",
children: [{ id: 848, name: "bla" }, { id: 959, name: "bla" }]
},
{ id: 433, name: "bla" },
{
id: 445,
name: "bla",
children: [
{ id: 443, name: "bla" },
{
id: 456,
name: "bla",
children: [
{
id: 97,
name: "bla"
},
{
id: 56,
name: "bla"
}
]
}
]
}
]
},
{
id: 15,
name: "bla",
children: [
{
id: 263,
name: "bla",
children: [{ id: 868, name: "bla" }, { id: 979, name: "bla" }]
},
{ id: 483, name: "bla" },
{
id: 445,
name: "bla",
children: [{ id: 423, name: "bla" }, { id: 436, name: "bla" }]
}
]
}
];
How would I grab a certain object by key that might be deeply nested, using recursion?
I have tried this, but this won't work for nesting deeper than 2 levels, it then just returns undefined:
const findItemNested = (arr, itemId, nestingKey) => {
for (const i of arr) {
console.log(i.id);
if (i.id === itemId) {
return i;
}
if (i[nestingKey]) {
findItemNested(i[nestingKey], itemId, nestingKey);
}
}
};
The result should be:
const res = findItemNested(array, 959, "children"); >> { id: 959, name: "bla" }
This can perhaps also be achieved using .find, or just to flatten the array (by the children key), but using recursion seems like the most logical solution to me. Does anybody have a solution to this?
Thanks in advance :).
You might use a recursive reduce:
const array=[{id:1,name:"bla",children:[{id:23,name:"bla",children:[{id:88,name:"bla"},{id:99,name:"bla"}]},{id:43,name:"bla"},{id:45,name:"bla",children:[{id:43,name:"bla"},{id:46,name:"bla"}]}]},{id:12,name:"bla",children:[{id:232,name:"bla",children:[{id:848,name:"bla"},{id:959,name:"bla"}]},{id:433,name:"bla"},{id:445,name:"bla",children:[{id:443,name:"bla"},{id:456,name:"bla",children:[{id:97,name:"bla"},{id:56,name:"bla"}]}]}]},{id:15,name:"bla",children:[{id:263,name:"bla",children:[{id:868,name:"bla"},{id:979,name:"bla"}]},{id:483,name:"bla"},{id:445,name:"bla",children:[{id:423,name:"bla"},{id:436,name:"bla"}]}]}];
const findItemNested = (arr, itemId, nestingKey) => (
arr.reduce((a, item) => {
if (a) return a;
if (item.id === itemId) return item;
if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
}, null)
);
const res = findItemNested(array, 959, "children");
console.log(res);
This should work:
function findByIdRecursive(array, id) {
for (let index = 0; index < array.length; index++) {
const element = array[index];
if (element.id === id) {
return element;
} else {
if (element.children) {
const found = findByIdRecursive(element.children, id);
if (found) {
return found;
}
}
}
}
}
You might also use recursion with Array.find like below
const array=[{id:1,name:"bla",children:[{id:23,name:"bla",children:[{id:88,name:"bla"},{id:99,name:"bla"}]},{id:43,name:"bla"},{id:45,name:"bla",children:[{id:43,name:"bla"},{id:46,name:"bla"}]}]},{id:12,name:"bla",children:[{id:232,name:"bla",children:[{id:848,name:"bla"},{id:959,name:"bla"}]},{id:433,name:"bla"},{id:445,name:"bla",children:[{id:443,name:"bla"},{id:456,name:"bla",children:[{id:97,name:"bla"},{id:56,name:"bla"}]}]}]},{id:15,name:"bla",children:[{id:263,name:"bla",children:[{id:868,name:"bla"},{id:979,name:"bla"}]},{id:483,name:"bla"},{id:445,name:"bla",children:[{id:423,name:"bla"},{id:436,name:"bla"}]}]}];
function findById(arr, id, nestingKey) {
// if empty array then return
if(arr.length == 0) return
// return element if found else collect all children(or other nestedKey) array and run this function
return arr.find(d => d.id == id)
|| findById(arr.flatMap(d => d[nestingKey] || []), id)
|| 'Not found'
}
console.log(findById(array, 12, 'children'))
console.log(findById(array, 483, 'children'))
console.log(findById(array, 1200, 'children'))
We use object-scan for most of our data processing. It's awesome for all sorts of things, but does take a while to wrap your head around. This is how one could answer your question:
// const objectScan = require('object-scan');
const find = (data, id) => objectScan(['**(^children$).id'], {
abort: true,
rtn: 'parent',
useArraySelector: false,
filterFn: ({ value }) => value === id
})(data);
const array=[{id:1,name:"bla",children:[{id:23,name:"bla",children:[{id:88,name:"bla"},{id:99,name:"bla"}]},{id:43,name:"bla"},{id:45,name:"bla",children:[{id:43,name:"bla"},{id:46,name:"bla"}]}]},{id:12,name:"bla",children:[{id:232,name:"bla",children:[{id:848,name:"bla"},{id:959,name:"bla"}]},{id:433,name:"bla"},{id:445,name:"bla",children:[{id:443,name:"bla"},{id:456,name:"bla",children:[{id:97,name:"bla"},{id:56,name:"bla"}]}]}]},{id:15,name:"bla",children:[{id:263,name:"bla",children:[{id:868,name:"bla"},{id:979,name:"bla"}]},{id:483,name:"bla"},{id:445,name:"bla",children:[{id:423,name:"bla"},{id:436,name:"bla"}]}]}];
console.log(find(array, 12));
// => { id: 12, name: 'bla', children: [ { id: 232, name: 'bla', children: [ { id: 848, name: 'bla' }, { id: 959, name: 'bla' } ] }, { id: 433, name: 'bla' }, { id: 445, name: 'bla', children: [ { id: 443, name: 'bla' }, { id: 456, name: 'bla', children: [ { id: 97, name: 'bla' }, { id: 56, name: 'bla' } ] } ] } ] }
console.log(find(array, 483));
// => { id: 483, name: 'bla' }
console.log(find(array, 959));
// => { id: 959, name: 'bla' }
console.log(find(array, 1200));
// => undefined
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan#13.7.1"></script>
Disclaimer: I'm the author of object-scan
You can do:
const array=[{id:1,name:"bla",children:[{id:23,name:"bla",children:[{id:88,name:"bla"},{id:99,name:"bla"}]},{id:43,name:"bla"},{id:45,name:"bla",children:[{id:43,name:"bla"},{id:46,name:"bla"}]}]},{id:12,name:"bla",children:[{id:232,name:"bla",children:[{id:848,name:"bla"},{id:959,name:"bla"}]},{id:433,name:"bla"},{id:445,name:"bla",children:[{id:443,name:"bla"},{id:456,name:"bla",children:[{id:97,name:"bla"},{id:56,name:"bla"}]}]}]},{id:15,name:"bla",children:[{id:263,name:"bla",children:[{id:868,name:"bla"},{id:979,name:"bla"}]},{id:483,name:"bla"},{id:445,name:"bla",children:[{id:423,name:"bla"},{id:436,name:"bla"}]}]}];
const findItemNested = (arr, itemId, nestingKey) => arr.reduce((a, c) => {
return a.length
? a
: c.id === itemId
? a.concat(c)
: c[nestingKey]
? a.concat(findItemNested(c[nestingKey], itemId, nestingKey))
: a
}, []);
const res = findItemNested(array, 959, "children");
if (res.length) {
console.log(res[0]);
}
This will use recursive find by level, it'll try to find the item in array and then call itself with the children of each item in the array:
New browsers will have Array.prototype.flatten but in this case I've added the flatten function separately.
const array = [{"id":1,"name":"bla","children":[{"id":23,"name":"bla","children":[{"id":88,"name":"bla"},{"id":99,"name":"bla"}]},{"id":43,"name":"bla"},{"id":45,"name":"bla","children":[{"id":43,"name":"bla"},{"id":46,"name":"bla"}]}]},{"id":12,"name":"bla","children":[{"id":232,"name":"bla","children":[{"id":848,"name":"bla"},{"id":959,"name":"bla"}]},{"id":433,"name":"bla"},{"id":445,"name":"bla","children":[{"id":443,"name":"bla"},{"id":456,"name":"bla","children":[{"id":97,"name":"bla"},{"id":56,"name":"bla"}]}]}]},{"id":15,"name":"bla","children":[{"id":263,"name":"bla","children":[{"id":868,"name":"bla"},{"id":979,"name":"bla"}]},{"id":483,"name":"bla"},{"id":445,"name":"bla","children":[{"id":423,"name":"bla"},{"id":436,"name":"bla"}]}]}];
const flatten = (arr) =>
arr.reduce((result, item) => result.concat(item), []);
const findBy = (findFunction, subItemsKey) => (array) =>
//array is empty (can be when children of children of children does not exist)
array.length === 0
? undefined //return undefined when array is empty
: array.find(findFunction) || //return item if found
findBy(findFunction, subItemsKey)(//call itself when item is not found
flatten(
//take children from each item and flatten it
//([[child],[child,child]])=>[child,child,child]
array.map((item) => item[subItemsKey] || []),
),
);
const findChildrenById = (array) => (value) =>
findBy((item) => item.id === value, 'children')(array);
const findInArray = findChildrenById(array);
console.log('found', findInArray(99));
console.log('not found', findInArray({}));
You need to iterate through your objects and then need to be parse each object using recursion. Try the answer mentioned here: JavaScript recursive search in JSON object
code:
`function findNode(id, currentNode) {
var i,
currentChild,
result;
if (id == currentNode.id) {
return currentNode;
} else {
// Use a for loop instead of forEach to avoid nested functions
// Otherwise "return" will not work properly
for (i = 0; i < currentNode.children.length; i += 1) {
currentChild = currentNode.children[i];
// Search in the current child
result = findNode(id, currentChild);
// Return the result if the node has been found
if (result !== false) {
return result;
}
}
// The node has not been found and we have no more options
return false;
}
}`

Javascript: Flatten any array values within object (nested)

I would like to flatten any array values within an object e.g. like sample below. The solution should not just apply to ecommerce but literally anything that could be in the object as an array type. Example:
var sample = {
price: "999",
description: "...",
ecommerce: {
products: [
{
brand: "apple",
category: "phone"
},
{
brand: "google",
category: "services"
}
]
}
};
And I would like the output to be:
{
price: "999",
description: "..."
ecommerce: {
products_1: {
brand: "apple",
category: "phone"
},
products_2: {
brand: "google",
category: "services"
}
}
}
What is the most efficient way to do this in JavaScript (ES6/7)?
Thanks in advance!
Updated due to comment and several minuses!!! Would be nice if those who were so quick to click minuses when the question was initially asked would revoke it!
I've tried this its completely wrong and I'm also sure theres a better functional way of doing this:
function flattenArray(array) {
var obj = array.reduce((acc, cur, i) => {
acc[i] = cur;
return acc;
}, {});
return obj;
}
function cleanObject(object) {
for (let key in object) {
let testObject = object[key];
if (Array.isArray(testObject)) {
testObject = flattenArray(testObject)
} else if (typeof(testObject) === 'object') {
testObject = cleanObject(testObject);
}
return testObject;
}
return object;
}
var clean = cleanObject(sample);
UPDATE 2: seeing as both solutions were so fixated on ecommerce how would the solution work if the next object was:
var sample = {
price: "999",
description: "...",
differentArray: [
{
brand: "apple",
category: "phone"
},
{
brand: "google",
category: "services"
}
]
};
Notice that not only is this different key its also at a different nesting level too.
A recursively applied Array#reduce based approach does the job for this kind of key-value bags, ... a first generic solution then might look like this one ...
function recursivelyMapArrayItemsToGenericKeys(collector, key) {
var
source = collector.source,
target = collector.target,
type = source[key];
if (Array.isArray(type)) {
type.forEach(function (item, idx) {
var
keyList = Object.keys(item || ''),
genericKey = [key, idx].join('_');
if (keyList.length >= 1) {
target[genericKey] = keyList.reduce(recursivelyMapArrayItemsToGenericKeys, {
source: item,
target: {}
}).target;
} else {
target[genericKey] = item;
}
});
} else if (typeof type !== 'string') {
var keyList = Object.keys(type || '');
if (keyList.length >= 1) {
target[key] = keyList.reduce(recursivelyMapArrayItemsToGenericKeys, {
source: type,
target: {}
}).target;
} else {
target[key] = type;
}
} else {
target[key] = type;
}
return collector;
}
var sample = {
price: "999",
description: "...",
ecommerce: {
products: [{
brand: "apple",
category: "phone"
}, {
brand: "google",
category: "services"
}, {
foo: [{
brand: "bar",
category: "biz"
}, {
brand: "baz",
category: "biz"
}]
}]
}
};
var result = Object.keys(sample).reduce(recursivelyMapArrayItemsToGenericKeys, {
source: sample,
target: {}
}).target;
console.log('sample : ', sample);
console.log('result : ', result);
.as-console-wrapper { max-height: 100%!important; top: 0; }
... within a next code sanitizing step one might get rid of duplicated logic, thus ending up with two functions and an alternating/reciprocal recursion ...
function recursivelyAssignItemsFromTypeByKeys(target, type, keyList, key) {
if (keyList.length >= 1) {
target[key] = keyList.reduce(recursivelyMapArrayItemsToGenericKeys, {
source: type,
target: {}
}).target;
} else {
target[key] = type;
}
}
function recursivelyMapArrayItemsToGenericKeys(collector, key) {
var
source = collector.source,
target = collector.target,
type = source[key];
if (Array.isArray(type)) {
type.forEach(function (item, idx) {
var
keyList = Object.keys(item || ''),
genericKey = [key, idx].join('_');
recursivelyAssignItemsFromTypeByKeys(target, item, keyList, genericKey);
});
} else if (typeof type !== 'string') {
var keyList = Object.keys(type || '');
recursivelyAssignItemsFromTypeByKeys(target, type, keyList, key);
} else {
target[key] = type;
}
return collector;
}
var sample = {
price: "999",
description: "...",
ecommerce: {
products: [{
brand: "apple",
category: "phone"
}, {
brand: "google",
category: "services"
}, {
foo: [{
brand: "bar",
category: "biz"
}, {
brand: "baz",
category: "biz"
}]
}]
}
};
var result = Object.keys(sample).reduce(recursivelyMapArrayItemsToGenericKeys, {
source: sample,
target: {}
}).target;
console.log('sample : ', sample);
console.log('result : ', result);
.as-console-wrapper { max-height: 100%!important; top: 0; }
What I'd do :
const sample = {
price: "999",
description: "...",
ecommerce: {
products: [
{
brand: "apple",
category: "phone"
},
{
brand: "google",
category: "services"
}
]
}
}
sample.ecommerce.products.forEach((p, i) => {
sample.ecommerce['products_' + i] = p
})
delete sample.ecommerce.products
console.log(sample)
Just reduce ecommerce array and destruct each element as you wish.
const sample = {
price: "999",
description: "...",
ecommerce: {
products: [
{
brand: "apple",
category: "phone"
},
{
brand: "google",
category: "services"
}
]
}
}
const flattenArray = (arr, key) =>
arr.reduce((prev, curr, index) => {
return {
...prev,
[`${key}_${index + 1}`]: curr,
}
}, {})
const result = {
...sample,
ecommerce: flattenArray(sample.ecommerce.products, 'products'),
}
console.log(result)

Categories

Resources