convert array into object name and values - javascript

I am trying to place my _rows values into my object value , however i have tried running a loop but i wasnt able to get the data out , the script i used is
let _columns = ["Name", "age", "phone"]
let _rows = [[{ value: 'john' }, { value: '22' }, { value: '999' }], [{ value: 'Bob' }, { value: '21' }, { value: '222' }]]
let res = {}
for (let i = 0; i < _rows.length; i++) {
for (let a = 0; a < _columns.length; a++) {
console.log(_rows[i][a].value)
}
res = _columns.reduce((acc,curr)=> (acc[curr]="data",acc),{});
console.log(res)
res = {}
}
on my console.log , it prints
The target output should be
{Name: 'john', age: '22', phone: '999'}
{Name: 'bob', age: '21', phone: '222'}

you can use
array.map to build another array from _rows
foreach value you have to check if columns exist
if (_columns[index]) {
if yes add in the new object the value under column name
res[_columns[index]] = property.value;
let _columns = ["Name", "age", "phone"]
let _rows = [[{ value: 'john' }, { value: '22' }, { value: '999' }], [{ value: 'Bob' }, { value: '21' }, { value: '222' }]];
let result = _rows.map(one => {
let res = {};
one.forEach((property, index) => {
if (_columns[index]) {
res[_columns[index]] = property.value;
}
});
return res;
});
console.log(result);

If you want to stick with reduce, just make this small change to get the actual value instead of the hardcode string "data". You need to use the optional parameter currentIndex of the reduce callback, then use the index to access the row item for the value.
let _columns = ["Name", "age", "phone"]
let _rows = [[{ value: 'john' }, { value: '22' }, { value: '999' }], [{ value: 'Bob' }, { value: '21' }, { value: '222' }]]
let res = {}
for (let i = 0; i < _rows.length; i++) {
for (let a = 0; a < _columns.length; a++) {
console.log(_rows[i][a].value)
}
res = _columns.reduce((acc,curr,index)=> (acc[curr]=_rows[i][index].value,acc),{});
console.log(res)
res = {}
}
However, when dealing with rows and columns in your case, since the array index is important, using old-school nested for-loop might be much more clear sometimes. My experience is, when you need the array index anyway, try not to be fancy and go for regular for-loop.
let _columns = ["Name", "age", "phone"]
let _rows = [[{ value: 'john' }, { value: '22' }, { value: '999' }], [{ value: 'Bob' }, { value: '21' }, { value: '222' }]]
for(let i = 0; i < _rows.length; i++)
{
let res = {};
for(let j = 0; j < _columns.length; j++)
{
res[_columns[j]] = _rows[i][j].value
}
console.log(res);
}

A double Arry.map will do the trick
let _columns = ["Name", "age", "phone"]
let _rows = [
[{ value: 'john' }, { value: '22' }, { value: '999' }],
[{ value: 'Bob' }, { value: '21' }, { value: '222' }]
];
const output = _rows.map((row) => row.map((item, index) => ({ [_columns[index]]: item.value })));
console.log(output)

Related

Remove duplicate from array

I want to remove each copy of object from array:
const object = [
{ label: "SUA", value: "sua" },
{ label: "SUA", value: "sua" },
{ label: "Florida", value: "florida" }
];
console.log(object.map(i=> [...new Set(i)]))
At the end i have to get like:
const object = [
{ label: "Florida", value: "florida" }
];
How to do this in my code?
You can use 2 for loops to achieve your functionality.
let result = [];
for(let i=0;i<object.length ;i++) {
let isDuplicate = false;
for(let j=0; j<object.length;j++) {
if(object[i].label === object[j].label && object[i].value === object[j].value && i !== j) {
isDuplicate = true;
}
}
if(!isDuplicate) result.push(object[i]);
}
Regardless of how many copies of each element you'd like to keep in the array, create a Map by definition Map<Location, number> and tabulate the number of occurrences of each Location object. Afterwards, take each element and append it to an array only once.
type Location = {label: string, value: string};
const object: Location[] = [
{ label: "SUA", value: "sua" },
{ label: "SUA", value: "sua" },
{ label: "Florida", value: "florida" }
];
const objects: Map<Location, number> = new Map();
for (const location of object)
if (objects.has(location))
objects.set(location, objects.get(location) + 1);
else
objects.set(location, 1);
const filtered: Location[] = [];
for (const location of objects)
if (location[1] === 1) // You change 1 to any value depending on how many copies of each you'd like.
filtered.push(location[0];
Note This is TypeScript for clarity, but the concept is the same.
You can use ES6 set -
const unique = [...new Set(object.map(({value}) => value))].map(e => object.find(({value}) => value == e));
console.log("unique",unique);
//[{label: "SUA", value: "sua"},{label: "Florida", value: "florida"}]
for your problem you can simply use reduce -
const uniq = object.reduce((a,b)=>{return a.value === b.value ? {} :[b]},[])
console.log(uniq);
//[{label: "Florida", value: "florida"}]
Short way:
const object = [
{ label: "SUA", value: "sua" },
{ label: "SUA", value: "sua" },
{ label: "Florida", value: "florida" }
];
const a = object.filter((v, i, a) => a.findIndex(t => (t.label ===
v.label && t.value === v.value)) === i);
console.log(a);
Simple solution with lodash
const object = [
{ label: "SUA", value: "sua" },
{ label: "SUA", value: "sua" },
{ label: "Florida", value: "florida" }
];
result = _.xor(_.uniqWith(object,_.isEqual),object)

How to make json data in Javascript?

I have an array which looks something like below:
[
{
name: "ReceiverId",
value: "1"
},
{name: "TransSequence", value: "KPJ7dL2pmx0njInNRAzUug"},
{
name: "email-address",
value: "xcv#cvb.com"
},
{
name: "mobile-number",
value: "9321313213"
},
{
name: "ReceiverId",
value: "2"
},
{
name: "TransSequence",
value: "KPJ7dL2pmx0njInNRAzUug"
},
{
name: "email-address",
value: "xcv#cvb.com"
}
]
Now I want to make my json data looks like this:
{
"MainData": [
{
"TransSequence": "wpiuVJw",
"ReceiverId": "1",
"ReceiverEmail": "xcv#cvb.com",
"ReceiverMobileNo": "9321313213",
},
{
"TransSequence": "xowpiuVJw",
"ReceiverId": "2",
"ReceiverEmail": "xcv#cvb.com",
"ReceiverMobileNo": "9321313213",
}
]
}
However I tried below code snippet:
mArr = []
obj = {};
for(var i=0; i<mainArr.length; i++){
// obj = {};
for(j = 0; j < 4; j++){
obj[mainArr[i].name] = mainArr[i].value
}
}
But above code snippet returns the last values only. However, I have also tried to convert into string based json but in last array it return as , which throws error while parsing it.
HELP WOULD BE APPRECIATED!!
Basing the code you tried, you are using js.
In js, you can use reduce to summarize the array. Use Object.assign to combine objects.
let arr = [{"name":"ReceiverId","value":"1"},{"name":"TransSequence","value":"KPJ7dL2pmx0njInNRAzUug"},{"name":"email-address","value":"xcv#cvb.com"},{"name":"mobile-number","value":"9321313213"},{"name":"ReceiverId","value":"2"},{"name":"TransSequence","value":"KPJ7dL2pmx0njInNRAzUug"},{"name":"email-address","value":"xcv#cvb.com"},{"name":"mobile-number","value":"9321231321"},{"name":"ReceiverId","value":"1"},{"name":"TransSequence","value":"KPJ7dL2pmx0njInNRAzUug"},{"name":"email-address","value":"xcv#cvb.com"},{"name":"mobile-number","value":"9321231321"},{"name":"ReceiverId","value":"2"}];
let propertyCount = 4;
let result = arr.reduce((c, v, i) => {
let o = Math.floor(i / propertyCount);
c[o] = c[o] || {};
c[o] = Object.assign(c[o], {[v.name]: v.value});
return c;
}, []);
console.log(result);
Here is my take:
const input = [
{name: "ReceiverId", value: "1"},
{name: "TransSequence", value: "KPJ7dL2pmx0njInNRAzUug"},
{name: "email-address", value: "xcv#cvb.com"},
{name: "mobile-number", value: "9321313213"},
{name: "ReceiverId", value: "2"},
{name: "TransSequence", value: "KPJ7dL2pmx0njInNRAzUug"},
{name: "email-address", value: "xcv#cvb.com"},
{name: "mobile-number", value: "9321231321"},
{name: "ReceiverId", value: "1"},
{name: "TransSequence", value: "KPJ7dL2pmx0njInNRAzUug"},
{name: "email-address", value: "xcv#cvb.com"},
{name: "mobile-number", value: "9321231321"},
{name: "ReceiverId", value: "2"}
];
let data = [];
input.forEach(e => {
// If it's a new data point, add it.
if (e.name === 'ReceiverId') {
data.push({
ReceiverId: e.value
})
// Add it to the last array.
} else {
data[data.length-1][e.name] = e.value
}
})
let output = {
MainData: data
}
// Your output
console.log(output)
.as-console-wrapper {min-height: 100%;}
Here is the correct code
let mainArr = [{"name":"ReceiverId","value":"1"},{"name":"TransSequence","value":"KPJ7dL2pmx0njInNRAzUug"},{"name":"email-address","value":"xcv#cvb.com"},{"name":"mobile-number","value":"9321313213"},{"name":"ReceiverId","value":"2"},{"name":"TransSequence","value":"KPJ7dL2pmx0njInNRAzUug"},{"name":"email-address","value":"xcv#cvb.com"},{"name":"mobile-number","value":"9321231321"},{"name":"ReceiverId","value":"1"},{"name":"TransSequence","value":"KPJ7dL2pmx0njInNRAzUug"},{"name":"email-address","value":"xcv#cvb.com"},{"name":"mobile-number","value":"9321231321"}];
const obj = {
MainData: [],
}
for(var i=0; i<mainArr.length / 4; i++){
const local = {}
for(j = i * 4; j < i * 4 + 4; j++){
local[mainArr[j].name] = mainArr[j].value
}
obj.MainData.push(local);
}
console.log(obj)

how to write a loop for search array

I want to learn how to make this code cleaner. I am using JavaScript.
Here is an Array of Objects:
var arr = [
{ key: 'qqqqq', value: '11' },
{ key: 'aaaaa', value: '121' },
{ key: 'bbbbb', value: '131' },
{ key: 'ccccc', value: '141' },
]
var obj = { key: 'cccc', value: '-fd-' };
My target is to find if obj in arr(it means, arritem.key == obj.key), if it does, update the value, otherwise append the obj to arr.
The idea of a directly is:
let has = false;
for(const item of arr) {
if(item.key == obj.key) {
item.value = obj.value;
has = true;
break;
}
}
if(!has) {
arr.push(l);
}
It's there a cleaner way to achieve ?
Unless you're restricted to using that given format for the array, you can achieve what you want by turning it into an object or key/value pair...
var data = {
'qqqqq': '11',
'aaaaa': '121',
'bbbbb': '131',
'ccccc': '141'
}
then to add or update a value...
data['ccccc'] = '-fd-'; // updates ccccc
data['eeeee'] = 'new'; // adds eeeee
You could use Array#find for getting the object or if not found push obj to the array.
var arr = [{ key: 'qqqqq', value: '11' }, { key: 'aaaaa', value: '121' }, { key: 'bbbbb', value: '131' }, { key: 'ccccc', value: '141' }],
obj = { key: 'cccc', value: '-fd-' };
temp = arr.find(o => o.key === obj.key);
if (temp) {
temp.value = obj.value;
} else {
arr.push(obj);
}
console.log(arr);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You've to first search if item exist in your array, you can use findIndex => if item is found just replace the value at the finded index by your new object else push it into your array.
var arr = [
{ key: 'qqqqq', value: '11' },
{ key: 'aaaaa', value: '121' },
{ key: 'bbbbb', value: '131' },
{ key: 'ccccc', value: '141' },
]
var obj = { key: 'cccc', value: '-fd-' };
var obj2 = { key: 'aaaaa', value: 'newValue' };
function updateOrPush(arr,obj){
var id = arr.findIndex(e => e.key == obj.key);
if(id > -1){
arr[id] = obj;
}
else{
arr.push(obj);
}
}
updateOrPush(arr,obj);
updateOrPush(arr,obj2);
console.log(arr)
Hope this code would be simpler
var arr = [
{ key: 'qqqqq', value: '11' },
{ key: 'aaaaa', value: '121' },
{ key: 'bbbbb', value: '131' },
{ key: 'ccccc', value: '141' },
]
var obj = { key: 'cccc', value: '-fd-' };
var objIndex = arr.findIndex(ele => ele.key === obj.key);
objIndex < 0 ? arr.push(obj) : arr[objIndex].value = obj.value;
console.log(arr);

Get index of parent object in nested object array

I have this array:
[
{
elements: [
{ id: '123', field: 'value' }
{ id: '456', field: 'value' }
]
}
{
elements: [
{ id: '789', field: 'value' }
]
}
]
Now I need to get the index of the first level object searching by an id:
searching for id = '456' should give me 0, id = '789' should give me 1
You can do this with findIndex() and some()
var arr = [{
elements: [{
id: '123',
field: 'value'
}, {
id: '456',
field: 'value'
}]
}, {
elements: [{
id: '789',
field: 'value'
}]
}]
var i = arr.findIndex(function(o) {
return o.elements.some(function(e) {
return e.id == 456;
})
})
console.log(i)
Get the feeling that something could be fixed to rethink this. But who knows.
456 should give u id 1 and so should 789 aswell.
var mapped = whatEverObject[0].elements.map(function(obj){ //0 = first
return obj.id;
})
console.log(mapped.indexOf(456)) // will give you 1 since id:123 is id 0 in the first elements array.
You can make a lookup table. It will be much faster if you do several lookups.
Live Example
var table = makeNestedLookupTable(example);
// table[789] would be 1 if the array in the question were "example"
function makeNestedLookupTable(data) {
return data.reduce(function(lookup, obj, topIndex) {
return obj.elements.reduce(function(lookup, element) {
lookup[element.id] = topIndex;
return lookup;
}, lookup);
}, {});
}
You can use this function getIndex which loops through the array and matches the id of the element with the given id and returns the index.This solution will work in all browsers.
var arr = [
{
elements: [
{ id: '123', field: 'value' }
{ id: '456', field: 'value' }
]
}
{
elements: [
{ id: '789', field: 'value' }
]
}
];
function getIndex(arr, id) {
var i, ii, len, elemlen;
for (i = 0, len = arr.length; i < len; i++) {
elements = arr[i].elements;
for (ii = 0, elemlen = elements.length; ii < elemlen; ii++) {
if (elements[ii].id === id) {
return i;
}
}
}
}
var index = getIndex(arr, '456');
Here is a generic code where you can send an array and the lookup attribute:
function giveLevel(a,attr){
for(var i=0;i<a.length;i++){
var o = a[i];
var tmp = JSON.stringify(o);
if(tmp.indexOf(attr)!==-1){
return i;
}
}
}
var a = [{elements: [
{ id: '123', field: 'value' },
{ id: '456', field: 'value' }
]
},
{
elements: [
{ id: '789', field: 'value' }
]
}
];
giveLevel(a,'"id":"789"'); // returns 1

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