Combine Array of Objects with similar keys conditionally using JavaScript
You can use Array.prototype.reduce
to aggregate the data by day and Object.keys
with Array.prototype.map
to format it to the desired output:
const data=[{day:'monday',time:'10:00 AM',type:'start',unit:1},{day:'monday',time:'11:30 AM',type:'end',unit:1},{day:'tuesday',time:'01:00 PM',type:'start',unit:1},{day:'tuesday',time:'06:00 PM',type:'end',unit:1},{day:'wednesday',time:'10:00 AM',type:'start',unit:1},{day:'wednesday',time:'06:00 PM',type:'end',unit:1}];
const grouped = data.reduce((all, {day, time, type, unit}) => {
if (!all.hasOwnProperty(day)) all[day] = { day, unit };
all[day][`${type}_time`] = time;
return all;
}, {});
const result = Object.keys(grouped).map((a,i) => ({sr_no: i + 1, ...grouped[a]}));
console.log(result);
Javascript: Merge Two Arrays of Objects, Only If Not Duplicate (Based on Specified Object Key)
You can create a set of IDs from initialData
and this will make "check if ID is already in initial data" faster - O(1):
var initialData = [{ 'ID': 1, 'FirstName': 'Sally' }, { 'ID': 2, 'FirstName': 'Jim' }, { 'ID': 3, 'FirstName': 'Bob' }];
var newData = [{ 'ID': 2, 'FirstName': 'Jim' }, { 'ID': 4, 'FirstName': 'Tom' }, { 'ID': 5, 'FirstName': 'George' }];
var ids = new Set(initialData.map(d => d.ID));var merged = [...initialData, ...newData.filter(d => !ids.has(d.ID))];
console.log(merged);
Conditionally merge array of objects
You can do it with reduce
const arrayToBeCompacted = [
{
section: "Section name 1",
path: ["segment1", "segment2"],
ids: ["id1"]
},
{
section: "Section name 1",
path: ["segment1", "segment2"],
ids: ["id2"]
},
{
section: "Section name2",
path: ["segment1", "segment2"],
ids: ["id3"]
},
{
section: "Another section",
path: ["segment1", "segment2"],
ids: ["id4"]
},
{
section: "Another section",
path: ["segment1", "segment2"],
ids: ["id5"]
},
]
const compacted = Object.values(arrayToBeCompacted.reduce((res, {section, path, ids}) => {
const key = section + path.join('|')
const existing = res[key] || {ids: [], section, path}
existing.ids = [...existing.ids, ...ids]
res[key] = existing
return res
}, {}))
console.log(compacted)
Combine array of string and number as object array conditionally
Try this vanilla js solution as well using filter
, Object.values
and map
var output = count.map((s, i) => ({
[fruits[i]]: s
})).filter(s => Object.values(s)[0]);
Demo
var fruits = [ "Apple", "Banana", "Apricot", "Bilberry"];
var count = [3, 5, 0, 2];
var output = count.map((s, i) => ({ [fruits[i]]: s})).filter(s => Object.values(s)[0]);
console.log(output);
Merge objects with the same id in an array by adding their numeric properties
You can use a combination of higher-level built-in functions like Object.keys
, Array#reduce
, and Array#map
to conditionally combine array entries when certain properties match.
var array = [{ Username: 'user1', Balance: '123'}, { Username: 'user2', Balance: '213'}, { Username: 'user1', Balance: '424'}]
var map = array.reduce(function (map, e) { map[e.Username] = +e.Balance + (map[e.Username] || 0) return map}, {})
var result = Object.keys(map).map(function (k) { return { Username: k, Balance: map[k] }})
console.log(result)
How to combine array of objects into one object and then create another object within that array based on a condition on the index
Please note, that your required output is IMPOSSIBLE - but if there's more than one object with the same key, the output could have an array of values for that key - see code
If each group of items in the original array begins with an object with a single key "Battery" - then this will perform the majicks for you
const arrayOfObjects = [{"Battery": "Battery"},{"batteryDetailsKey": ["Serial Number","Type","Part Number",]},{"batteryDetailsVal": ["HJ3CA19347410218LJ98 100 QC","Extended Range","4P94-Q001",]},{"Modules": "Modules"},{"moduleDetailsKey": ["Serial Number","Part Number","Cell Count",]},{"moduleDetailsVal": ["83675327350061093222581609899001","LJ98-10C779-A01","32",]},{"assetSeparator": "assetSeparator"},{"Battery": "Battery"},{"batteryDetailsKey": ["Serial Number","Type","Part Number"]},{"batteryDetailsVal": ["HJ3CA19347410218LJ98 101 QC","Extended Range","4P94-Q002"]},{"Modules": "Modules"},{"moduleDetailsKey": ["Serial Number","Part Number","Cell Count"]},{"moduleDetailsVal": ["83675327350061093222581609899002","LJ98-10C779-A02","28"]},{"moduleDetailsVal": ["83675327350061093222581609899003","LJ98-10C779-A03","27"]},{"assetSeparator": "assetSeparator"},{"Battery": "Battery"},{"batteryDetailsKey": ["Serial Number","Type","Part Number",]},{"batteryDetailsVal": ["HJ3CA19347410218LJ98 102 QC","Extended Range","4P94-Q003",]},{"Modules": "Modules"},{"moduleDetailsKey": ["Serial Number","Part Number","Cell Count",]},{"moduleDetailsVal": ["83675327350061093222581609899004","LJ98-10C779-A01","32",]}];
const shapeIWantArrayOfObjects = [];
let currentOutput;
for (let object of arrayOfObjects) {
if (Object.keys(object).join('') === 'Battery') {
currentOutput = {};
shapeIWantArrayOfObjects.push(currentOutput);
}
Object.entries(object).forEach(([key, val]) => {
const existing = currentOutput[key];
if (!existing) {
currentOutput[key] = val;
} else {
if (!Array.isArray(currentOutput[key][0])) {
currentOutput[key] = [currentOutput[key]];
}
currentOutput[key].push(val);
}
});
}
console.log(shapeIWantArrayOfObjects);
.as-console-wrapper {max-height: 100%!important; top:0; }
.as-console-row::after { display:none !important; }
How to merge array of keys and arrays of values into an object?
use this one.
var a = ["F", "M"];
var b = ["female", "male"];
var c = ["fa-female", "fa-male"];
var resultArray = [];
for(var i = 0; i < a.length; i++) {
resultArray [a[i]] = [b[i], c[i]];
}
Related Topics
Calculate the Bounding Box'S X, Y, Height and Width of a Rotated Element Via JavaScript
Reinitialize Slick Js After Successful Ajax Call
Calculating Sum of Checked Checkboxes
Weird Behaviour With on Click Event Binding; Event Not Firing
How to Tell If a Dom Element Is Visible in the Current Viewport
Parsing Error: Unexpected Token, Expected ","
How to Pass Checkbox State to Onclick Function in React
Generate and Download CSV File With PHP and Ajax
Reactjs How to Call a Component Function from Another Function on the Same File
Datatables/Tabletools: Format Data as Text When Exporting to Excel
Passing Value from Java to JavaScript
Postman Test - Validating String Values in an Object in an Array
Vuetify: How to Preselect Active Tab
How to Parse Excel (Xls) File in Javascript/Html5
"Cannot Read Property of Undefined" When Using Chrome.Tabs or Other Chrome API in Content Script
How to Generate Event Handlers With Loop in JavaScript