Creating new object from 2 existing objects - javascript

I have the following:
var identificationIDs = [
{
"HolderID": "1A000714",
"TempIssueID": "1A000700"
}
]
Which I am trying to update to include a new object "ExtendedID" with some values to look like below:
var identificationIDs = [
{
"HolderID": "1A000714",
"TempIssueID": "1A000700",
"ExtendedID": [
"1A000714",
"1A000700"
]
}
]
Running into issues with trying to push HolderID and TempIssueID into the new object.
Here is my code:
// Simplify variable name:
var userID = identificationIDs;
// Create new object and assign values:
for (var i = 0; i < userID.length; i++) {
userID[i].HolderID = userID[i].ID;
userID[i].ExtendedID = userID[i].HolderID.push(TempIssueID);
}
console.log(userID);

You can use Javascript's built-in spread syntax to help you out.
If you're playing around with arrays, minor changes should be made. Take a look at an example:
let identificationIDs = {
"HolderID": "1A000714",
"TempIssueID": "1A000700"
}
let extendedId = [
"1A000714",
"1A000700"
]
let newIdentificationIds = {...identificationIDs, ExtendedID: extendedId};
console.log(newIdentificationIds)

You can try these following ways.
var identificationIDs = [
{
HolderID: "1A000714",
TempIssueID: "1A000700",
},
];
// Using `Object.values`
const result = identificationIDs.map((obj) => ({
...obj,
ExtendedID: Object.values(obj),
}));
// Alternatively, use destructuring
const result2 = identificationIDs.map(({ HolderID, TempIssueID }) => ({
HolderID,
TempIssueID,
ExtendedID: [HolderID, TempIssueID],
}));
console.log(result);
console.log(result2);

Related

Fastest way to clean path collisions in array of strings

This is a hard one to explain, but here goes. I need to clean an array of 'path' strings where if a path has sub properties it not include the top level property. but only the child properties
E.g
[
'firstName',
'address',
'address.local.addressLine1',
'address.local.addressLine2',
'address.local',
]
Should become:
[
'firstName',
'address.local.addressLine1',
'address.local.addressLine2',
'address.local',
]
I have a fairly verbose function kind of working so far, but looking to see if there is a more elegant/better solution than this:
function cleanCollisions(array) {
var output = [];
// return [...new Set(array)];
var map = array.reduce(function(set, field) {
if (!Boolean(field)) {
return set;
}
////////////////
var rootKey = field.split('.')[0];
if(!set[rootKey]) {
set[rootKey] =[];
}
var count = field.split('.').length -1;
if(count) {
set[rootKey].push(field);
}
return set;
}, {})
for(const key in map) {
value = map[key];
if(value.length) {
output.push(value);
} else {
output.push(key);
}
}
////////////////
return output.flat();
}
I'd first iterate over the array to extract the top property of all strings that have sub properties, then filter out all those top properties.
const input = [
'firstName',
'address',
'address.local.addressLine1',
'address.local.addressLine2',
'address.local',
];
const topLevelProps = new Set();
for (const str of input) {
const match = str.match(/^(.*?)\./);
if (match) {
topLevelProps.add(match[1]);
}
}
const output = input.filter(str => !topLevelProps.has(str));
console.log(output);
A variation of the answer by CertainPerformance but using filter and map instead of regex:
const paths = [
'firstName',
'address',
'address.local.addressLine1',
'address.local.addressLine2',
'address.local',
];
const roots = paths.filter(p => p.includes('.')).map(p => p.split('.')[0]);
const cleansed = paths.filter(p => p.includes('.') || !roots.includes(p));
console.log(cleansed);

Trying to concat 2 objects and destruct it into a new data structure

Given the following objects:
obj1 - { min: 86, down: 95, up: 95, max: 88, … }
obj2 - { right: 35 }
I've written the following code:
Object.keys(response).forEach(key => {
let newLabel = this.getLabel(key);
let labelPanel = this.getPanel(key);
let newPair = {
[newLabel]: response[key]
};
let secondPair = {
panel: labelPanel
};
const newObj = Object.assign(newPair, secondPair);
newDataStructure = { ...newDataStructure,
...newObj
};
});
And what I'm trying to do is to run over the given object, and create a new object with the updated key name.
For example:
min: 77 ---> Minimum: 77
I am also trying to get a value and set it to the 'panel' key, then I want to create a new object with these 2 keys, like this:
{ Minimum: 99, panel: "Budget" }
By doing this destructure:
newDataStructure = { ...newDataStructure, ...newObj};
Result: I'm getting the new data structure like the following:
{Minimum: 99, panel: "Budget", down: 95, up: 95, max: 88,....}
Only the first part is getting the 'panel' key and value, but the rest are values from the 1st object.
How can I create an array of objects like this:
[{Minimum: 99, panel: "Budget"}, {Maximum: 88, panel: "Budget"}, {....}, {....}]
You need to make an array first and then keep pushing your newObj in it. Try
let newResponse = [];
Object.keys(response).forEach(key => {
let newLabel = this.getLabel(key);
let labelPanel = this.getPanel(key);
let newPair = {
[newLabel]: response[key]
};
let secondPair = {
panel: labelPanel
};
const newObj = Object.assign(newPair, secondPair);
newResponse.push(newObj);
});

How to remove "[" and "]" signs from array in Javascript

I'm using react.js for building my dashboard
I want to convert an array like this (old version) [ {...}, {...}, {...} ] into this (new version) {...}, {...}, {...} in javascript
So I can put the new version of the array inside a JSON array like this [ {...}, newArray ]
I know a map function returns an array and I know it's a silly question but I wonder how
here is my code:
const siteProfilesList = ['ABC', 'DEF', 'GHI']
const pagesList = ['Dashboard', 'Routes', 'Payload']
const siteProfileNavigationsList = siteProfilesList.map((item, index) => {
let menu = {}
menu['_tag'] = 'CSidebarNavDropdown'
menu['name'] = item
menu['_children'] = pagesList.map((pageItem, pageIndex) => {
let pageMenu = {}
pageMenu['_tag'] = 'CSidebarNavItem'
pageMenu['name'] = pageItem
pageMenu['to'] = `/${pageItem.toLowerCase()}/location=${item.toLowerCase()}`
return pageMenu
})
return menu
})
const navigations = [
{
_tag: 'CSidebarNavTitle',
_children: ['Site Profile']
},
siteProfileNavigationsList
]
export default navigations
I know it's a silly question but I just wonder about the solution.
Is that what you want? I use flat().
const siteProfilesList = ["ABC", "DEF", "GHI"];
const pagesList = ["Dashboard", "Routes", "Payload"];
const siteProfileNavigationsList = siteProfilesList.map((item, index) => {
let menu = {};
menu["_tag"] = "CSidebarNavDropdown";
menu["name"] = item;
menu["_children"] = pagesList.map((pageItem, pageIndex) => {
let pageMenu = {};
pageMenu["_tag"] = "CSidebarNavItem";
pageMenu["name"] = pageItem;
pageMenu[
"to"
] = `/${pageItem.toLowerCase()}/location=${item.toLowerCase()}`;
return pageMenu;
});
return menu;
});
const navigations = [
{
_tag: "CSidebarNavTitle",
_children: ["Site Profile"],
},
siteProfileNavigationsList,
];
console.log(navigations.flat());
I think what you're looking for is the destructuring spread syntax.
const arr = [x, y, z]
const anotherArr = [a, b]
const combined = [...anotherArr, ...arr] // [a, b, x, y, z]
The ... "removes" the brackets arround the array.
you don't need to remove the brackets, you just need to concatenate your two arrays https://www.w3schools.com/jsref/jsref_concat_array.asp

How to add attribute to the root of JSON object consists of array of objects?

How to add attribute to the root of JSON object consists of array of objects?
If my JSON object something like that:
[
{
"Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9",
"Name":"W",
"NumberOfWorkHours":8,
"NumberOfShortDays":1,
"WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99"
},
{
"Id":"5c267601-fcf2-4735-9e49-b4def3981648",
"Name":"S",
"NumberOfWorkHours":6,
"NumberOfShortDays":0,
"WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580"
}
]
I do the following:
worktimeJSON.Id = $('.Js-WorkTime-id').val();
worktimeJSON.Name = $('.Js-WorkTime-name').val();
worktimeJSON.NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val();
And make sure that the jQuery fetching data from the inputs but this doesn't work.
This will change property of all object in array if you want to change in particular then use index for this for exp->
worktimeJSON[0].Id = $('.Js-WorkTime-id').val();
worktimeJSON[0].Name = $('.Js-WorkTime-name').val();
worktimeJSON[0].NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val();
var worktimeJSON = [
{
"Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9",
"Name":"W",
"NumberOfWorkHours":8,
"NumberOfShortDays":1,
"WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99"
},
{
"Id":"5c267601-fcf2-4735-9e49-b4def3981648",
"Name":"S",
"NumberOfWorkHours":6,
"NumberOfShortDays":0,
"WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580"
}
];
worktimeJSON = worktimeJSON.map(function(val){
val.Id = $('.Js-WorkTime-id').val();
val.Name = $('.Js-WorkTime-name').val();
val.NumberOfAvailableRotations = $('.Js-WorkTime-rotations').val();
return val;
});
Push can do the job.
let worktimeJSON = [
{
"Id":"f2ac41c5-b214-48f6-ad40-9fc35c1aaad9",
"Name":"W",
"NumberOfWorkHours":8,
"NumberOfShortDays":1,
"WorkTimeRegulationId":"f5833075-2847-4cc3-834d-6138dd0dcd99"
},
{
"Id":"5c267601-fcf2-4735-9e49-b4def3981648",
"Name":"S",
"NumberOfWorkHours":6,
"NumberOfShortDays":0,
"WorkTimeRegulationId":"8d14580e-278f-41d1-9239-8874be792580"
}
];
worktimeJSON.push
({
id: "someID",
name: "toto",
WorkTimeRegulationId: 42
});
console.log(worktimeJSON);
I structure my object like this:
let WorkTimeRegulationViewModelJSON = {
Id: $('.Js-WorkTimeRegulation-id').val(),
Name: $('.Js-WorkTimeRegulation-name').val(),
NumberOfAvailableRotations: $('.Js-WorkTimeRegulation-rotations').val(),
AssignedWorkTimes: JSON.parse(worktimeJSON)
};

flatten array of object into an array

const x = [{
name:"abc",
},{
name:"xyz"
}]
how to turn above array of object into an array?
expected output
x = ['abc','xyz']
I know I can do a native loop, use push to a new empty array but I'm looking for one line es2015/es6 or even lodash method
Simply use the map function:
const y = x.map(c => c.name);
const x = [{
name:"abc",
},{
name:"xyz"
}]
const names = x.map(c => c.name);
console.log(names);
Solution in Lodash (very similar to plain js):
const x = [{
name:"abc",
},{
name:"xyz"
}]
const names _.map(x, 'name'); // => ['abc', 'xyz']
Edit
as requested also in plain js
const names = x.map(el => el.name);
or
const names = x.map(function(el) {
return el.name;
});
x = [{
name:"abc",
},{
name:"xyz"
}];
x = x.map(function (value) {
return value.name;
});
Use map()
let res = x.map(o => o.name);

Categories

Resources