Convert json to other json structure - javascript

I have an array of objects with this structure:
const treeData = [
{ 0: ["0-0", "0-1"] },
{ 1: ["1-0", "1-1"] }
]
It could be deeper but array data would be always json or strings
const treeData = [
{ 0: ["0-0", "0-1"] },
{ 1: ["1-0", "1-1"] },
2,
3
]
I would like to get something like this:
const treeDataResult = [
{
label: "0",
value: "0",
children: [
{
label: "0-0",
value: "0-0"
},
{
label: "0-1",
value: "0-1",
}
]
},
{
label: "1",
value: "1",
children: [
{
label: "1-0",
value: "1-0",
},
{
label: "1-1",
value: "1-1",
}
]
},
{
label: "2",
value: "2"
},
{
label: "3",
value: "3"
}
]
My code right now is this:
const treeData = [
{ "0": ["0-0", "0-1"] },
{ "1" : ["1-0", "1-1"] }
];
const convertNode = (parentNode) =>
parentNode.map(
childnode => {
if (typeof(childNode) === 'string')
return {
label: childNode,
value: childNode
}
else
return
childNode.map((key, val) =>
({
label: key,
value: key,
children: convertNode(val)
})
)
}
)
var treeDataResult = convertNode(treeData);
console.log(treeDataResult);

If JSON.parse is used to get the data, you can try something like this:
var j = '[ { "0": ["0-0", "0-1"] }, { "1": ["1-0", "1-1"] }, 2, 3 ]'
var o = JSON.parse(j, (k, v) => (k = v.constructor) === Array ? v :
k !== Object ? ({ label: v, value: v }) :
({ label: k = Object.keys(v)[0], value: k, children: v[k] }) )
console.log( o )

If the shape of your data is correct I've used reduce and map to get the data into the correct shape and the rest operator so that the objects are in one array
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
const treeData = [
{
0: ["0-0", "0-1"]
},
{
1: ["1-0", "1-1"]
},
{
2: null
},
{
3: []
},
{
4: ["0-1"]
}
]
const changeShape = data => {
return data.reduce((prev, curr) => [...prev, ...shape(curr)], []);
}
const shape = item => Object.keys(item).map(key => data(item, key));
const data = (item, key) => {
return !item[key] || !item[key].length > 0 ?
labelValue(key) :
{
...labelValue(key),
children: item[key].map(i => labelValue(i))
}
}
const labelValue = v => {
return {
label: v,
value: v
}
}
console.log(changeShape(treeData))

const treeData = [
{ "0": ["0-0", "0-1"] },
{ "1" : ["1-0", "1-1"] }
];
const convertNode = (parentNode) => {
console.log(parentNode)
return parentNode.map(
childNode => {
if (typeof childNode === 'string')
return {
label: childNode,
value: childNode
}
else
return {
label: Object.entries(childNode)[0][0],
value: Object.entries(childNode)[0][0],
children: convertNode(Object.entries(childNode)[0][1])
}
}
)
}

a primitive solution
const treeData = [
{ 0 : ["0-0", "0-1"] },
{ 1 : ["1-0", "1-1"] }
]
let treeDataResult = [];
for(i = 0; i < treeData.length; i++) {
let current = treeData[i],
label = Object.getOwnPropertyNames(current),
obj = {
label: label,
value: label,
children: []
}
for(j = 0; j < current[i].length; j++) {
let childData = current[i][j],
child = {
label : childData,
value : childData
}
obj.children.push(child)
}
treeDataResult.push(obj)
}
console.log(JSON.stringify(treeDataResult, null, 4));

Related

Merge an array by comparing the array of objects inside the array

I have the following array
var array = [
{
group: "FL",
list: [
{ key: "A", value: "Alaska" },
{ key: "B", value: "Brazil" },
{ key: "C", value: "California" }
]
},
{
group: "NZ",
list: [
{ key: "A", value: "Alaska" },
{ key: "B", value: "Brazil" },
{ key: "D", value: "Delhi" }
]
},
{
group: "QA",
list: [
{ key: "A", value: "Alaska" },
{ key: "B", value: "Brazil" },
{ key: "C", value: "California" }
]
}
]
I need to check the list array and if all the objects in the list array are exately same , then I need to merge it as below:
[
{
group: "FL,QA",
list: [
{ key: "A", value: "Alaska" },
{ key: "B", value: "Brazil" },
{ key: "C", value: "California" }
]
},
{
group: "NZ",
list: [
{ key: "A", value: "Alaska" },
{ key: "B", value: "Brazil" },
{ key: "D", value: "Delhi" }
]
}
]
I tried this by using reduce method to loop over the array and two other functions to compare the objects, but somehow its not working
array.reduce(async(acc, item) => {
const exist = await compareObjects(acc, item);
if (exist) {
acc[exist.index].group= exist.group + ',' + item.group;
} else {
acc.push(item)
}
return acc;
}, [])
async function compareObjects(o1, o2) {
for (let i = 0; i < o1.length; i++) {
const value = await checkObjs(o1[i].list, o2.list);
if(value) { return {index:i , group: o1[i].group} }
}
}
function checkObjs(arr1, arr2) {
return arr1.length === arr2.length && arr1.every((el, i) => objectsEqual(el, arr2[i]))
}
const objectsEqual = (o1, o2) =>
Object.keys(o1).length === Object.keys(o2).length
&& Object.keys(o1).every(p => o1[p] === o2[p]);
Any help would be appreciated . Thanks
Your use of async is what's tripping you up here, and I'm not sure your reason for using it.
To make your code work as is you need to await the accumulator on each iteration, and assign the result of the reduce() to something.
var array = [ { group: 'FL', list: [ { key: 'A', value: 'Alaska' }, { key: 'B', value: 'Brazil' }, { key: 'C', value: 'California' }, ], }, { group: 'NZ', list: [ { key: 'A', value: 'Alaska' }, { key: 'B', value: 'Brazil' }, { key: 'D', value: 'Delhi' }, ], }, { group: 'QA', list: [ { key: 'A', value: 'Alaska' }, { key: 'B', value: 'Brazil' }, { key: 'C', value: 'California' }, ], }, ];
function checkObjs(arr1, arr2) {
const objectsEqual = (o1, o2) =>
Object.keys(o1).length === Object.keys(o2).length && Object.keys(o1).every((p) => o1[p] === o2[p]);
return arr1.length === arr2.length && arr1.every((el, i) => objectsEqual(el, arr2[i]));
}
async function compareObjects(o1, o2) {
for (let i = 0; i < o1.length; i++) {
const value = await checkObjs(o1[i].list, o2.list);
if (value) {
return { index: i, group: o1[i].group };
}
}
}
// assign the result of reduce to a variable
const result = array.reduce(async (acc, item) => {
acc = await acc; // await the returned accumulator Promise
const exist = await compareObjects(acc, item);
if (exist) {
acc[exist.index].group = exist.group + ',' + item.group;
} else {
acc.push(item);
}
return acc;
}, []);
result.then((r) => console.log(r));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use Array.reduce() to create a map of your input objects.
We'll create a function getListKey() to create a unique key based on each object list.
Once we have our map, we can use Object.values() to get the array result:
var array = [ { group: "FL", list: [ { key: "A", value: "Alaska" }, { key: "B", value: "Brazil" }, { key: "C", value: "California" } ] }, { group: "NZ", list: [ { key: "A", value: "Alaska" }, { key: "B", value: "Brazil" }, { key: "D", value: "Delhi" } ] }, { group: "QA", list: [ { key: "A", value: "Alaska" }, { key: "B", value: "Brazil" }, { key: "C", value: "California" } ] } ]
function getListKey(list) {
return JSON.stringify(list.sort(({ key: a }, { key: b }) => a.localeCompare(b)));
}
const result = Object.values(array.reduce((acc, { group, list }) => {
const key = getListKey(list);
if (!acc[key]) {
acc[key] = { group, list };
} else {
acc[key].group += "," + group;
}
return acc;
}, {}))
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Another way of approaching this is again using Array.reduce(), but using the lodash _.isEqual() function for list comparison. This performs a deep comparison. We'd use this along with Array.find() to get any list duplicate.
var array = [ { group: "FL", list: [ { key: "A", value: "Alaska" }, { key: "B", value: "Brazil" }, { key: "C", value: "California" } ] }, { group: "NZ", list: [ { key: "A", value: "Alaska" }, { key: "B", value: "Brazil" }, { key: "D", value: "Delhi" } ] }, { group: "QA", list: [ { key: "A", value: "Alaska" }, { key: "B", value: "Brazil" }, { key: "C", value: "California" } ] } ]
const result = array.reduce((acc, cur) => {
const foundItem = acc.find(item => _.isEqual(item.list, cur.list));
if (foundItem) {
foundItem.group += `,${cur.group}`;
} else {
acc.push(cur);
}
return acc;
}, [])
console.log('Result:', result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js" referrerpolicy="no-referrer"></script>
I think the way I would suggest going about this problem is by breaking it apart and (hopefully) using library functions to tackle some of the more complicated bits. For example with lodash you could say
import isEqual from "lodash/isEqual";
const arr = [
{
group: "FL",
list: [
{ key: "A", value: "Alaska" },
{ key: "B", value: "Brazil" },
{ key: "C", value: "California" }
]
},
{
group: "NZ",
list: [
{ key: "A", value: "Alaska" },
{ key: "B", value: "Brazil" },
{ key: "D", value: "Delhi" }
]
},
{
group: "QA",
list: [
{ key: "A", value: "Alaska" },
{ key: "B", value: "Brazil" },
{ key: "C", value: "California" }
]
}
];
function groupBy<T, R>(
a: T[],
iteritem: (t: T) => R,
compare: (a: R, b: R) => boolean = isEqual
) {
const groups: T[][] = [];
const rs = a.map(iteritem);
for (let i = 0; i < rs.length; i++) {
let added = false;
const r = rs[i];
for (let j = 0; j < groups.length; j++) {
if (compare(r, iteritem(groups[j][0]))) {
groups[j].push(a[i]);
added = true;
break;
}
}
if (!added) {
groups.push([a[i]]);
}
}
return groups;
}
const grouped = groupBy(arr, (a) => a.list);
const combined = [];
for (const g of grouped) {
combined.push({
group: g.map(({ group }) => group).join(","),
list: g[0].list
});
}
console.log(JSON.stringify(combined, undefined, 2));
This isn't as much of a one off answer since groupBy could be reused. I originally wanted to use groupBy from lodash but it doesn't accept a custom equality function.
This is one possible solution:
const sorted = [];
for (let i = 0; i < groups.length; i++) {
const identicalLists = [];
for (let j = i; j < groups.length; j++) {
const isIdentical =
JSON.stringify(groups[i].list) === JSON.stringify(groups[j].list);
const found = !!sorted.flat().find((item) => item === groups[j].group);
if (isIdentical && !found) {
identicalLists.push(groups[j].group);
}
}
if (identicalLists.length > 0) {
sorted.push(identicalLists);
}
}
const answer = sorted.map((item) => {
const first = groups.find((group) => group.group === item[0]);
return { group: item, list: first.list };
});
Reduce does not work with async/await. If you don't have async code - one that fetches something from an API or uses data from a Promise, you should remove the async/await, because it is synchronous.
If the code you have uses some async API - try using something like:
export const reduceAsync = async (array, transformer, initialvalue) => {
let accumolator = typeof initialValue !== 'undefined' ? initialValue : array[0];
for (let i = 0; i < array.length; i++) {
accumolator = await transformer(accumolator, array[i], i, array);
}
return accumolator;
};
The function above is reusable and follows the spec defined here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

How do I sort an object with children properties?

I have an object that represents a tree:
const obj = {
"1": {
id: "1",
children: ["1-1", "1-2"]
},
"1-1": {
id: "1-1",
children: ["1-1-1", "1-1-2"]
},
"1-2": {
id: "1-2",
children: []
},
"1-1-1": {
id: "1-1-1",
children: []
},
"1-1-2": {
id: "1-1-2",
children: []
}
};
The result is a list similar to:
<ul>
<li>
1
<ul>
<li>
1.1
<ul>
<li>1.1.1</li>
<li>1.1.2</li>
</ul>
</li>
<li>
1.2
</li>
</ul>
</li>
</ul>
What I need is to transform the object above to an array where items go in the order they do in the list representation, i.e. ['1', '1-1', '1-1-1', '1-1-2', '1-2']. Ids can be any so I can't rely on them. It's the order of items in the children property that matters.
Update
The final result should be ['1', '1-1', '1-1-1', '1-1-2', '1-2'] i.e. the order they come in the list from the top to the bottom.
I use DFS to parse. It can sort any depth data. (You can try the obj2)
const obj = {
"1": {
id: "1",
children: ["1-1", "1-2"]
},
"1-1": {
id: "1-1",
children: ["1-1-1", "1-1-2"]
},
"1-2": {
id: "1-2",
children: []
},
"1-1-1": {
id: "1-1-1",
children: []
},
"1-1-2": {
id: "1-1-2",
children: []
}
};
const obj2 = {
"2": {
id: "2",
children: ["2-1", "2-2", "2-3"]
},
"2-1": {
id: "2-1",
children: ["2-1-1", "2-1-2"]
},
"2-2": {
id: "2-2",
children: []
},
"2-3": {
id: "2-3",
children: []
},
"2-1-1": {
id: "2-1-1",
children: ["2-1-1-1", "2-1-1-2"]
},
"2-1-2": {
id: "2-1-2",
children: ["2-1-2-1"]
},
"2-1-1-1": {
id: "2-1-1-1",
children: []
},
"2-1-1-2": {
id: "2-1-1-2",
children: []
},
"2-1-2-1": {
id: "2-1-2-1",
children: []
},
};
/* DFS */
function sort(id) {
if (!sorted.includes(id)) {
sorted.push(id);
obj[id].children.forEach(sub => {
sort(sub);
});
}
}
/* MAIN */
let sorted = [];
for (let [id, value] of Object.entries(obj)) {
sort(id);
}
console.log(sorted.flat());
const obj={1:{id:"1",children:["1-1","1-2"]},"1-1":{id:"1-1",children:["1-1-1","1-1-2"]},"1-2":{id:"1-2",children:[]},"1-1-1":{id:"1-1-1",children:[]},"1-1-2":{id:"1-1-2",children:[]}};
const output = Object.keys(obj)
// remove every non root
Object.entries(obj).forEach(el => el[1].children.forEach(child => {
let index = output.indexOf(child)
if (index !== -1) {
output.splice(index, 1)
}
}))
for (let i = 0; i < output.length; i++) {
// for each get it's children
let children = obj[output[i]].children
// push them just behind it
output.splice(i + 1, 0, ...children)
}
console.log(output)
You could try a recursive call with the base condition to ignore the traversed node
const obj = {
"1": {
id: "1",
children: ["1-1", "1-2"],
},
"1-1": {
id: "1-1",
children: ["1-1-1", "1-1-2"],
},
"1-2": {
id: "1-2",
children: [],
},
"1-1-1": {
id: "1-1-1",
children: [],
},
"1-1-2": {
id: "1-1-2",
children: [],
},
}
function traverse(obj) {
const res = []
const traversed = {}
function getChildren(id) {
if (traversed[id]) {
return
}
res.push(id)
traversed[id] = true
obj[id].children.forEach((childId) => getChildren(childId))
}
for (const id in obj) {
getChildren(id)
}
return res
}
console.log(traverse(obj))
Hope this is what you are expecting ?
let ans = []
function recursiveCallObj(key){
!ans.includes(key) ? ans.push(key) : ""
for(let i=0; i< obj[key].children.length; i++){
if(!ans.includes(obj[key].children[i])){
recursiveCallObj(obj[key].children[i])
}
else{
return
}
}
}
for(let [key, value] of Object.entries(obj)){
if(value.children.length > 0){
recursiveCallObj(key)
}
else{
!ans.includes(key) ? ans.push(key) : ""
}
}
console.log(ans)

Javascript get full index of nested object

const items = [
{ id: 'item1',
children: [
{ id: 'item1-1',
children: [
{ id: 'item1-1-1' },
{ id: 'item1-1-2' },
{ id: 'item1-1-3'
children: [
{ id: 'item1-1-3-1'}
]
},
]
},
{ id: 'item1-2',
children: [
{ id: 'item1-2-1' }
]
}
]
},
{ id: 'item2' }
]
What I want to is like below,
function getFullDepthOfObject(){
...
}
getFullIndexOfObject('item1') =====> return '1'
getFullIndexOfObject('item1-2') =====> return '1-2'
getFullIndexOfObject('item1-1-1') =====> return '1-1-1'
getFullIndexOfObject('item1-1-2') =====> return '1-1-2'
getFullIndexOfObject('item2') ===> return '2'
I have struggled with this too much time, But I couldn't make it. I think I should stack each of parent index, But I don't know how to get its parent. Is there a way to do this?
Not parse of id string. Each id has randomic string. The id like item1-2 is for easier demonstration.
I think my way is too verbose...
I tried like ...
// Get Full Index of item1-1
// First, get the target's depth.
var depth = 0;
function getDepthOfId(object, id) {
var level;
if (object.id === id) return 1;
object.children && object.children.some(o => level = getDepthOfId(o, id));
return level && level + 1;
}
depth = getDepthOfId(items[0], 'item1-1');
console.log('depth === ', depth)
// Then, iterate recursively with length of depth.
var indexStacks = [];
function getNestedIndexOfId(obj, id, index) {
if (obj.id === id) {
indexStacks = [index, ...indexStacks]
return index;
}
if (obj.children) {
depth++;
obj.children.map((child, i) => {
getNestedIndexOfId(child, id, i)
})
}
}
// I can get the inner index, but I can't get its parent id.
// I don't know how to this..
function getParentId(obj, id){
// ...?
var parentId;
return parentId;
}
for(var i=0; i<depth; i++){
getNestedIndexOfId('...')
}
// full path will be
indexStacks.join('-')
const items = [
{ id: 'item1',
children: [
{ id: 'item1-1',
children: [
{ id: 'item1-1-1' },
{ id: 'item1-1-2' },
{ id: 'item1-1-3',
children: [
{ id: 'item1-1-3-1'}
]
}
]
},
{ id: 'item1-2',
children: [
{ id: 'item1-2-1' }
]
}
]
},
{ id: 'item2' }
];
const searchIt = (node, search, path = '', position = 0) => {
if (node.id && node.id === search) {return path !== '' ? `${path}-${position}` : position;}
if (!node.children) {return false}
const index = node.children.findIndex((x) => x.id && x.id === search);
if (index >= 0) {
return path !== '' ? `${path}-${index + 1}` : index + 1;
}
for (let i = 0; i < node.children.length; i++) {
const result = searchIt(node.children[i], search, path !== '' ? `${path}-${i+1}` : i + 1, i);
if (result){
return result;
}
}
return false;
};
console.log(searchIt({children: items}, 'item1-1'));
console.log(searchIt({children: items}, 'item1-1-1'));
console.log(searchIt({children: items}, 'item1-1-2'));
console.log(searchIt({children: items}, 'item1-1-3'));
console.log(searchIt({children: items}, 'item1-1-3-1'));
console.log(searchIt({children: items}, 'item1-2-1'));
console.log(searchIt({children: items}, 'item1-1-3-2'));
console.log(searchIt({children: items}, 'item1-2-2'));
console.log(searchIt({children: items}, 'item3'));
You could take an recursive and iterative approach. On found, the path is returned from the most inner object to the outer call of the function.
function getPath(array, id) {
var result;
array.some((o, i) => {
var temp;
if (o.id === id) return result = `${i + 1}`;
if (temp = getPath(o.children || [], id)) return result = `${i + 1}-${temp}`;
});
return result;
}
const items = [{ id: 'item1', children: [{ id: 'item1-1', children: [{ id: 'item1-1-1' }, { id: 'item1-1-2' }, { id: 'item1-1-3', children: [{ id: 'item1-1-3-1'}] }] }, { id: 'item1-2', children: [{ id: 'item1-2-1' }] }] }, { id: 'item2' }];
console.log(getPath(items, 'item1')); // '1'
console.log(getPath(items, 'item1-2')); // '1-2'
console.log(getPath(items, 'item1-1-1')); // '1-1-1'
console.log(getPath(items, 'item1-1-2')); // '1-1-2'
console.log(getPath(items, 'item2')); // '2'
You can solve this problem using recursion. I have edited my code block and made it into a testable snippet. I had to fix an error in your data (missing comma or something don't remember).
const items = [
{ id: 'itemA',
children: [
{ id: 'item1-1',
children: [
{ id: 'item1-1-1' },
{ id: 'item1-1-2' },
{ id: 'item1-1-3', children: [ { id: 'item1-1-3-1'} ] },
]
},
{ id: 'item1-2', children: [ { id: 'item1-2-1' } ] },
],
},
{ id: 'item2' }
];
const getItemLevel = (targetKey, item, depth = 0) => {
if (item.id === targetKey) return depth;
let foundLevel = null;
if (item.children) {
item.children.forEach((child) => {
if (foundLevel) return;
foundLevel = getItemLevel(targetKey, child, depth +1);
})
}
return foundLevel;
}
console.log(getItemLevel('item1-1-1', { id:'root', children: items }));
console.log(getItemLevel('item2', { id:'root', children: items }));
console.log(getItemLevel('item1-1-3-1', { id:'root', children: items }));
console.log(getItemLevel('keydoesnotexist', { id:'root', children: items }));
a simple way:
const recursiveFind = (arr, id, res = {indexes: [], found: false}) => {
if (!Array.isArray(arr)) return res
const index = arr.findIndex(e => e.id === id)
if (index < 0) {
for (let i = 0; i < arr.length; i++) {
res.indexes.push(i+1)
const childIndexes = recursiveFind(arr[i].children, id, res)
if (childIndexes.found){
return childIndexes
}
}
}
else {
res.found = true
res.indexes.push(index+1)
}
return res
}
recursiveFind(items, 'item1-1-2').indexes.join('-')
If it's ok to use Lodash+Deepdash, then:
let path;
_.eachDeep(items,(val,key,parent,context)=>{
if(path) return false;
if(val.id=='item1-1-2'){
path=context.path;
return false;
}
},{tree:true,pathFormat:'array'});
console.log(_(path).without('children').map(v=>parseInt(v)+1).join('-'));
Here is a codepen for this

How to turn dot notation string into an object in Javascript

I'm trying to turn a dot notation string into an object, for example given
[{
key: 'app.team.instance',
value: 'some value1'
}, {
key: 'app.team.instance.obj',
value: 'some value'
}, {
key: 'app.team.app.some',
value: 'some value'
}, {
key: 'app.service.awesome.more',
value: 'more values'
}]
I would like to turn it an object like to get
{
"team": {
"instance": "some value1",
"server": {
"obj": "some value"
},
"app": {
"some": "some value"
}
},
"service": {
"awesome": {
"more": "more values"
}
}
}
This's what I have tried using the following function. Looking at my function what have I missed or should improve?
function createObjFromRows(skip, key, value, obj) {
const ARRAY_KEYS = key.split('.');
const ARRAY_LENGTH = ARRAY_KEYS.length;
let i = skip ? 1 : 0;
for (; i < ARRAY_LENGTH; i++) {
if (i < (ARRAY_LENGTH - 1)) {
if (!obj.hasOwnProperty(ARRAY_KEYS[i])) { obj[ARRAY_KEYS[i]] = {}; }
} else {
obj[ARRAY_KEYS[i - 1]][ARRAY_KEYS[i]] = value;
}
}
}
This's what I get currently.
{
team: {
instance: 'some value1'
},
server: {
obj: 'some value'
},
app: {
some: 'some value'
},
service: {},
awesome: {
more: 'more values'
}
}
You can use array.prototype.reduce :
var datas = [ {key: 'app.team.instance', value: 'some value1'}, {key: 'app.team.server.obj', value: 'some value'}, {key: 'app.team.app.some',value: 'some value'}, {key: 'app.service.awesome.more', value: 'more values'}];
var res = datas.reduce((m, o) => {
var keys = o.key.split('.');
var cur = m;
keys.forEach((key, i) => {
if (i < keys.length - 1) {
cur[key] = cur[key] || {};
cur = cur[key];
} else {
cur[key] = o.value;
}
});
return m;
}, {});
console.log(res);
You could split the given key strings and save the last key for the assignment of the value after iterating the keys to the nested property.
var data = [{ key: 'app.team.instance', value: 'some value1' }, { key: 'app.team.server.obj', value: 'some value' }, { key: 'app.team.app.some', value: 'some value' }, { key: 'app.service.awesome.more', value: 'more values' }],
result = data.reduce(function (r, o) {
var path = o.key.split('.'),
last = path.pop();
path.reduce(function (p, k) {
return p[k] = p[k] || {};
}, r)[last] = o.value;
return r;
}, {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Merge JavaScript objects in array with same key

What is the best way to merge array contents from JavaScript objects sharing a key in common?
How can array in the example below be reorganized into output? Here, all value keys (whether an array or not) are merged into all objects sharing the same name key.
var array = [
{
name: "foo1",
value: "val1"
}, {
name: "foo1",
value: [
"val2",
"val3"
]
}, {
name: "foo2",
value: "val4"
}
];
var output = [
{
name: "foo1",
value: [
"val1",
"val2",
"val3"
]
}, {
name: "foo2",
value: [
"val4"
]
}
];
Here is one option:-
var array = [{
name: "foo1",
value: "val1"
}, {
name: "foo1",
value: ["val2", "val3"]
}, {
name: "foo2",
value: "val4"
}];
var output = [];
array.forEach(function(item) {
var existing = output.filter(function(v, i) {
return v.name == item.name;
});
if (existing.length) {
var existingIndex = output.indexOf(existing[0]);
output[existingIndex].value = output[existingIndex].value.concat(item.value);
} else {
if (typeof item.value == 'string')
item.value = [item.value];
output.push(item);
}
});
console.dir(output);
Here is another way of achieving that goal:
var array = [{
name: "foo1",
value: "val1"
}, {
name: "foo1",
value: [
"val2",
"val3"
]
}, {
name: "foo2",
value: "val4"
}];
var output = array.reduce(function(o, cur) {
// Get the index of the key-value pair.
var occurs = o.reduce(function(n, item, i) {
return (item.name === cur.name) ? i : n;
}, -1);
// If the name is found,
if (occurs >= 0) {
// append the current value to its list of values.
o[occurs].value = o[occurs].value.concat(cur.value);
// Otherwise,
} else {
// add the current item to o (but make sure the value is an array).
var obj = {
name: cur.name,
value: [cur.value]
};
o = o.concat([obj]);
}
return o;
}, []);
console.log(output);
2021 version
Using reduce to aggregate data.
Using logical nullish assignment only assigns if acc[name] is nullish (null or undefined).
Using Array.isArray to determines whether the passed value is an Array.
var arrays = [{ name: "foo1",value: "val1" }, {name: "foo1", value: ["val2", "val3"] }, {name: "foo2",value: "val4"}];
const result = arrays.reduce((acc, {name, value}) => {
acc[name] ??= {name: name, value: []};
if(Array.isArray(value)) // if it's array type then concat
acc[name].value = acc[name].value.concat(value);
else
acc[name].value.push(value);
return acc;
}, {});
console.log(Object.values(result));
Using lodash
var array = [{name:"foo1",value:"val1"},{name:"foo1",value:["val2","val3"]},{name:"foo2",value:"val4"}];
function mergeNames (arr) {
return _.chain(arr).groupBy('name').mapValues(function (v) {
return _.chain(v).pluck('value').flattenDeep();
}).value();
}
console.log(mergeNames(array));
Here is a version using an ES6 Map:
const arrays = [{ name: "foo1",value: "val1" }, {name: "foo1", value: ["val2", "val3"] }, {name: "foo2",value: "val4"}];
const map = new Map(arrays.map(({name, value}) => [name, { name, value: [] }]));
for (let {name, value} of arrays) map.get(name).value.push(...[value].flat());
console.log([...map.values()]);
Use lodash "uniqWith". As shown below
let _ = require("lodash");
var array = [
{ name: "foo1", value: "1" },
{ name: "foo1", value: "2" },
{ name: "foo2", value: "3" },
{ name: "foo1", value: "4" }
];
let merged = _.uniqWith(array, (pre, cur) => {
if (pre.name == cur.name) {
cur.value = cur.value + "," + pre.value;
return true;
}
return false;
});
console.log(merged);
// output: [{ name: "foo1", value: "1,2,4" }, { name: "foo2", value: "3" }];
Using reduce:
var mergedObj = array.reduce((acc, obj) => {
if (acc[obj.name]) {
acc[obj.name].value = acc[obj.name].value.isArray ?
acc[obj.name].value.concat(obj.value) :
[acc[obj.name].value].concat(obj.value);
} else {
acc[obj.name] = obj;
}
return acc;
}, {});
let output = [];
for (let prop in mergedObj) {
output.push(mergedObj[prop])
}
It's been a while since this question was asked, but I thought I'd chime in as well. For functions like this that execute a basic function you'll want to use over and over, I prefer to avoid longer-written functions and loops if I can help it and develop the function as a one-liner using shallow Array.prototype functions like .map() and some other ES6+ goodies like Object.entries() and Object.fromEntries(). Combining all these, we can execute a function like this relatively easily.
First, I take in however many objects you pass to the function as a rest parameter and prepend that with an empty object we'll use to collect all the keys and values.
[{}, ...objs]
Next, I use the .map() Array prototype function paired with Object.entries() to loop through all the entries of each object, and any sub-array elements each contains and then either set the empty object's key to that value if it has not yet been declared, or I push the new values to the object key if it has been declared.
[{},...objs].map((e,i,a) => i ? Object.entries(e).map(f => (a[0][f[0]] ? a[0][f[0]].push(...([f[1]].flat())) : (a[0][f[0]] = [f[1]].flat()))) : e)[0]
Finally, to replace any single-element-arrays with their contained value, I run another .map() function on the result array using both Object.entries() and Object.fromEntries(), similar to how we did before.
let getMergedObjs = (...objs) => Object.fromEntries(Object.entries([{},...objs].map((e,i,a) => i ? Object.entries(e).map(f => (a[0][f[0]] ? a[0][f[0]].push(...([f[1]].flat())) : (a[0][f[0]] = [f[1]].flat()))) : e)[0]).map(e => e.map((f,i) => i ? (f.length > 1 ? f : f[0]) : f)));
This will leave you with the final merged object, exactly as you prescribed it.
let a = {
a: [1,9],
b: 1,
c: 1
}
let b = {
a: 2,
b: 2
}
let c = {
b: 3,
c: 3,
d: 5
}
let getMergedObjs = (...objs) => Object.fromEntries(Object.entries([{},...objs].map((e,i,a) => i ? Object.entries(e).map(f => (a[0][f[0]] ? a[0][f[0]].push(...([f[1]].flat())) : (a[0][f[0]] = [f[1]].flat()))) : e)[0]).map(e => e.map((f,i) => i ? (f.length > 1 ? f : f[0]) : f)));
getMergedObjs(a,b,c); // { a: [ 1, 9, 2 ], b: [ 1, 2, 3 ], c: [ 1, 3 ], d: 5 }
Try this:
var array = [{name:"foo1",value:"val1"},{name:"foo1",value:["val2","val3"]},{name:"foo2",value:"val4"},{name:"foo2",value:"val5"}];
for(var j=0;j<array.length;j++){
var current = array[j];
for(var i=j+1;i<array.length;i++){
if(current.name = array[i].name){
if(!isArray(current.value))
current.value = [ current.value ];
if(isArray(array[i].value))
for(var v=0;v<array[i].value.length;v++)
current.value.push(array[i].value[v]);
else
current.value.push(array[i].value);
array.splice(i,1);
i++;
}
}
}
function isArray(myArray) {
return myArray.constructor.toString().indexOf("Array") > -1;
}
document.write(JSON.stringify(array));
This work too !
var array = [
{
name: "foo1",
value: "val1",
},
{
name: "foo1",
value: ["val2", "val3"],
},
{
name: "foo2",
value: "val4",
},
];
let arr2 = [];
array.forEach((element) => { // remove duplicate name
let match = arr2.find((r) => r.name == element.name);
if (match) {
} else {
arr2.push({ name: element.name, value: [] });
}
});
arr2.map((item) => {
array.map((e) => {
if (e.name == item.name) {
if (typeof e.value == "object") { //lets map if value is an object
e.value.map((z) => {
item.value.push(z);
});
} else {
item.value.push(e.value);
}
}
});
});
console.log(arr2);
const exampleObj = [{
year: 2016,
abd: 123
}, {
year: 2016,
abdc: 123
}, {
year: 2017,
abdcxc: 123
}, {
year: 2017,
abdcxcx: 123
}];
const listOfYears = [];
const finalObj = [];
exampleObj.map(sample => {    
listOfYears.push(sample.year);
});
const uniqueList = [...new Set(listOfYears)];
uniqueList.map(list => {   
finalObj.push({
year: list
});
});
exampleObj.map(sample => {    
const sampleYear = sample.year;  
finalObj.map((obj, index) => {     
if (obj.year === sampleYear) {        
finalObj[index] = Object.assign(sample, obj);       
}  
}); 
});
The final object be [{"year":2016,"abdc":123,"abd":123},{"year":2017,"abdcxcx":123,"abdcxc":123}]
const array = [{ name: "foo1", value: "val1" }, {name: "foo1", value: ["val2", "val3"] }, {name: "foo2", value: "val4"}];
const start = array.reduce((object, {name}) => ({...object, [name]: []}), {});
const result = array.reduce((object, {name, value}) => ({...object, [name]: [object[name], [value]].flat(2)}), start);
const output = Object.entries(result).map(([name, value]) => ({name: name, value: value}));
console.log(output);
try this :
var array = [
{
name: "foo1",
value: "val1"
}, {
name: "foo1",
value: [
"val2",
"val3"
]
}, {
name: "foo2",
value: "val4"
}
];
var output = [
{
name: "foo1",
value: [
"val1",
"val2",
"val3"
]
}, {
name: "foo2",
value: [
"val4"
]
}
];
bb = Object.assign( {}, array, output );
console.log(bb) ;
A much more easier approach is this 2022:
var array = [
{
name: "foo1",
value: "val1"
}, {
name: "foo1",
value: [
"val2",
"val3"
]
}, {
name: "foo2",
value: "val4"
}
];
var output = [
{
name: "foo1",
value: [
"val1",
"val2",
"val3"
]
},
{
name: "foo2",
value: [
"val4"
]
}
];
function mergeBasedOnKey(list){
let c = Object.values(list.reduce((a, b) => {
a[b.name] = a[b.name] || {name: b.name, value: []}
if(typeof(b['value']) == "string"){
a[b.name].value.push(b['value'])
}
else{
a[b.name].value = [...a[b.name].value, ...b.value]
}
return a
}, {}))
return c
}
let ans = mergeBasedOnKey(array)
console.log(ans)
I was looking for a quick, almost "one-liner" answer in this thread, provided that this is a trivial but common exercise.
I couldn't find any for my like. The other answers are fine but I am not much into boilerplate.
So, let me add one, then:
o = array.reduce((m,{name:n,value:v})=>({...m,[n]:[...m[n]||[],v].flat(1)}),{})
output = Object.entries(o).map(([n,v])=>({name:n,value:v}))
var array = [
{ name: "foo1", value: "val1"},
{ name: "foo1", value: ["val2","val3"] },
{ name: "foo2", value: "val4" }
]
o=array.reduce((m,{name:n,value:v})=>({...m,[n]:[...m[n]||[],v].flat(1)}),{})
output=Object.entries(o).map(([n,v])=>({name:n,value:v}))
console.log(output)

Categories

Resources