Delete keys from an array of objects in javascript - javascript

I have an array of objects as shown below
[{
'0': 'RECORD_KEY',
'1': 'FIRST_TOUCH_DATE_TIME',
'2': 'ISA_SENDER_ID'
},
{
'0': '00208851228_1',
'1': '2020-02-19 13:08:20.0',
'2': 'CCA'
}, {
'0': ''
}
]
I want to remove the key and the last object which is null.
So the result would be -
[{
'0': 'RECORD_KEY',
'1': 'FIRST_TOUCH_DATE_TIME',
'2': 'ISA_SENDER_ID'
},
{
'0': '00208851228_1',
'1': '2020-02-19 13:08:20.0',
'2': 'CCA'
}
]
So each object would represent a row of data.
How can I possibly do this in node.js?

Your desird outcome is not valid JS. What you need is a nested array(array of arrays):
const arr =[
{
'0': 'RECORD_KEY',
'1': 'FIRST_TOUCH_DATE_TIME',
'2': 'ISA_SENDER_ID'
},
{
'0': '00208851228_1',
'1': '2020-02-19 13:08:20.0',
'2': 'CCA'
},
{ '0': '' }
]
const mainArr = []
for(let item of arr){
const subArr = []
for(let prop in item){
if(!item[prop]){
continue;
}
subArr.push(item[prop])
}
if(subArr.length){
mainArr.push(subArr)
}
}
One note: Please next time provide a formatted code snippet

Related

JavaScript | How can I remove an element of an array using it's value instead of it's index?

const currentMaterialsId = [1,2,3,4,5]
const materials = {
0: {
id: 1
},
1: {
id: 2
},
2: {
id: 3
},
3: {
id: 4
},
4: {
id: 5
}
}
I am trying to remove an element in the currenMaterialsId array but when I use the index of the materials object, things don't go as planned. If I use the id as the start number in splice, it still uses that number and searches for the matching index in the array instead of the value. Please help.
here's what I have at the moment.
let sortedMaterialIndex = currentMaterialsId.sort()
sortedMaterialIndex.splice(materialIndex, 1)
dispatch(removeElementCurrentMaterialsArray(selectedSheet,
sortedMaterialIndex))
ok I'm sorry it wasn't clear guys.
What I am trying to do is remove an element in currentMaterialsId that has the same value as the id in the object materials. However, when I use the id from materials as a starting number, for example
const materialId = dashboard.sheets[selectedSheet].materialProperties[materialIndex].id
currentMaterialsId.splice(materialId, 1)
it searches currentMaterialsId array for an index that matches the passed starting number(materialId), which is what I do not want.
so let's say I want to delete 2 from currentMaterialsId, could I use splice? and if I use splice, what should I pass as a starting number?
I hope this makes my question clearer.
Thanks for the responses!
What I am trying to do is remove an element in currentMaterialsId that
has the same value as the id in the object materials.
could I use splice?
You appear to be trying to do something like this:
so.js:
const materials = {
'0': { id: 1 },
'1': { id: 2 },
'2': { id: 3 },
'3': { id: 4 },
'4': { id: 5 }
};
console.log(materials);
// id from materials
let i = 1;
console.log(i);
let id = materials[i].id;
console.log(id);
function removeMaterialsId(id, materialsId) {
for (let i = 0; i < materialsId.length; i++) {
if (materialsId[i] === id) {
materialsId.splice(i--, 1);
}
}
}
let materialsId = [];
// remove materialsId elements with id from materials
console.log();
materialsId = [ 1, 2, 3, 4, 5 ];
console.log(id, materialsId);
removeMaterialsId(id, materialsId);
console.log(materialsId);
// remove materialsId elements with id from materials
console.log();
materialsId = [ 1, 2, 2, 3, 4, 2, 5 ];
console.log(id, materialsId);
removeMaterialsId(id, materialsId);
console.log(materialsId);
$ node so.js
{
'0': { id: 1 },
'1': { id: 2 },
'2': { id: 3 },
'3': { id: 4 },
'4': { id: 5 }
}
1
2
2 [ 1, 2, 3, 4, 5 ]
[ 1, 3, 4, 5 ]
2 [ 1, 2, 2, 3, 4, 2, 5 ]
[ 1, 3, 4, 5 ]
$
First off, perhaps you want to store your objects in an array, like this(?):
const materials = [
{
id: 1
},
{
id: 2
},
{
id: 3
},
{
id: 4
},
{
id: 5
}
];
Then you can remove from array using filter:
const materialToRemove = { id: 1 }
const materialsWithOneRemoved = materials
.filter(material => material.id !== materialToRemove.id);
Note that filter creates a new array, it does not change the existing array. You can however overwrite the existing array with a new one if you want to:
// materials like above, but with let instead of const
let materials = ...
const materialToRemove = { id: 1 }
materials = materials
.filter(material => material.id !== materialToRemove.id);
If you want to have your objects in an object like you have in your question, you need to first convert it to an array before you can filter. You can do that using e.g. Object.values.
Your question is far from clear, but indexOf may be a solution:
const sortedMaterialIndex = currentMaterialsId.sort();
const index = sortedMaterialIndex.indexOf(materialIndex);
if (index > -1) {
sortedMaterialIndex.splice(index, 1);
}
See How can I remove a specific item from an array?
I would recommend using the filter array function to achieve what you want.
let idToRemove = 1
let filteredMaterials = materials.filter((v) => v.id !== idToRemove);
console.log(filteredMaterials)

Nested dictionary to list of strings - typeScript

I have a nested dictionary which I want to convert to a list of strings.
e.g.
I have this input:
var group = {
'5': {
'1': {
'1': [1,2,3],
'2': [1]
},
'2':{
'1': [2,4],
'2': [1]
}
},
'1': {
'1':{
'1':[1,2,5],
'2':[1]
},
'2':{
'1':[2,3]
}
}
};
I want this output:
a = ["5.1.1.1","5.1.1.2","5.1.1.3"..... "1.2.1.3"]
I started with this recursive function:
function printValues(obj) {
for (var key in obj) {
console.log(key)
if (typeof obj[key] === "object") {
printValues(obj[key]);
} else {
console.log(obj[key]);
}
}
}
But t doesn't work yet..
You could take an iterative and recursive approach and get the most nested items first and build the wanted strings.
How does it work?
It takes from an object all entries (key/value pairs) and pushes a spreaded array to the result set.
The array for spreading is either
an array of values or
an array from calling the function again with the object v as parameter
Both arrays are mapped by taking the key k from the object and an item from the array for getting the wanted style n.m.
For example take a sub { 1: [2, 4], 2: [1] } object and get an array of key/values.
[
[1, [2, 4]],
[2, [1]]
]
This is the result of the first iteration of reduce. The order is the logical run from the inside:
yes, it's an array,
take v with [2, 4],
map this value together with k 1,
get array of ['1.2', '1.4'],
spread this array and
push each element as parameter.
Then take the second loop and get ['1.2', '1.4', '2.1'].
This result is taken as value from getPathes and mapped with the actual key in front of each string.
The result is a build by a depth-first search for getting the most inner array and put the key in front of each item.
function getPathes(object) {
return Object.entries(object).reduce((r, [k, v]) => {
r.push(...(Array.isArray(v) ? v : getPathes(v)).map(l => `${k}.${l}`));
return r;
}, []);
}
var group = { 5: { 1: { 1: [1, 2, 3], 2: [1] }, 2: { 1: [2, 4], 2: [1] } }, 1: { 1: { 1: [1, 2, 5], 2: [1] }, 2: { 1: [2, 3] } } },
result = getPathes(group);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use Object.entries with this recursive function:
var group = {
'5': {
'1': {
'1': [1,2,3],
'2': [1]
},
'2':{
'1': [2,4],
'2': [1]
}
},
'1': {
'1':{
'1':[1,2,5],
'2':[1]
},
'2':{
'1':[2,3]
}
}
};
let r = []
const getPaths = (p, v) => {
if (Array.isArray(v)) {
v.forEach(e => r.push([...p, e].join('.')))
} else {
Object.entries(v).forEach(([k, v]) => getPaths([...p, k], v))
}
}
getPaths([], group)
console.log(r)

Modifying an array of objects in JavaScript

I have an array of objects like this
[ { '0': { notify_item: '1' } },
{ '1': { notify_item: '2' } },
{ '2': { notify_item: '3' } } ]
Now I want to replace '0' with some Text like 'Invoice' and the value of that '0' key with value like this { 'sms': true,email:'false' }.
And I want to replace every key with some text and their value with something like this { 'sms': true,email:'false' }
so after replacing I want something like this
[ { 'Invoice': { 'sms': true,email:'false' } },
{ 'ManualReminder': { 'sms': true,email:'false' },
{ 'AutomaticReminder': { 'sms': true,email:'false' } ]
I am not able to understand I have tried the splice method but it is not working. Please give some hint
Iterate through the array using Array.map function. In map function you can use switch statements to match the appropriate values and return the desired output.
var arr = [{
'0': { notify_item: '1' }
},
{
'1': { notify_item: '2' }
},
{
'2': { notify_item: '3' }
}];
var modifiedArr = arr.map(function(item) {
var newItem = {};
for ( var key in item) {
var newItemKey = getKey(key);
var newItemValue = getValue(item[key]);
}
newItem[newItemKey] = newItemValue;
return newItem;
});
console.log(modifiedArr);
function getKey (key) {
switch(key) {
case '0':
return 'Invoice';
case '1':
return 'ManualReminder';
case '2':
return 'AutomaticReminder';
default:
return 'default';
}
}
function getValue (value) {
switch(value.notify_item) {
case '1':
return { 'sms': true,email:'false' };
case '2':
return { 'sms': true,email:'false' };
case '3':
return { 'sms': true,email:'false' };
default:
return 'default';
}
}
[ { 'Invoice': { 'sms': true,email:'false' } },
{ 'ManualReminder': { 'sms': true,email:'false' },
{ 'AutomaticReminder': { 'sms': true,email:'false' } ]
This is a job for map.
It's also harder than it should be because the structure of your data is quite weird. Wouldn't something like { notification_type: 0, notify_item: 1 } be easier to work with?
It may not be needed to convert data, you may just get new result.
Maybe something like this will help you.
var input = [ { '0': { notify_item: '1' } },
{ '1': { notify_item: '2' } },
{ '2': { notify_item: '3' } } ];
var keyMap = {'0': 'Invoice', '1': 'ManualReminder', '2': 'AutomaticReminder'};
var result = Object.keys(input).map(function (key) {
var item = {},
value = input[key]; //{notify_item:'1'} for first iteration
//do your logic to convert {notify_item: '1' | '2' | '3'}
item[keyMap[key]] = ''; //to whatever you need
return item;
});
console.log(result);

Convert and combine arrays in javascript

Hey I need your help in respect of converting arrays in javascript. Please look on my output data:
Answers: {
'0': { '0': 'ans 1' },
'1': { '0': 'ans 11', '1': 'ans 22', '2': 'ans 33' }
}
correctAnswers: {
'1': { '0': true, '1': true }
}
And I would like if indexes doesn't match set false, so I expect following array:
convertArray = [[false], [true, true, false]]
For this task I use following function
var choiceBoolean = [];
for(corrAns in Answers){
let tempArr = [];
Object.keys(Answers[corrAns]).forEach(k =>
tempArr[k] = correctAnswers[corrAns][k] || false)
choiceBoolean.push(Array.apply(null, tempArr).map(Boolean))
}
Unfortunately I receive error TypeError: Cannot read property '0' of undefined
You could map the keys from answer with another mapped array from the inner keys by checking correct answers.
This solution works with a check if the correct answer exist and then it checks the inner key.
correct[k] && correct[k][l] || false
^^^^^^^^^^ check first if exists
^^^^^^^^^^^^^ take a truthy value
^^^^^ if not take false
var answers = { 0: { 0: 'ans 1' }, 1: { 0: 'ans 11', 1: 'ans 22', 2: 'ans 33' } },
correct = { 1: { 0: true, 1: true } },
result = Object
.keys(answers)
.map(k => Object.keys(answers[k]).map(l => correct[k] && correct[k][l] || false));
console.log(result);

Mapping an org chart into a hash table

Hey all I'm trying to take an array of objects(employees) and map them to a new object in order to depict the hierarchy of the org. So each manager would have a key and an array attached to the key holding all the names of their reports.
I'm unsure why I am unable to push my employee names to their respective manager's array. This seems to set my object keys to arrays rather than 1,2,3,4.
Anyone pointers would be appreciated.
Repl.it: https://repl.it/JeMh/2
let data = [
{
name: 'ceo',
id: 1,
mgr: null,
},
{
name: 'vp1',
id: 2,
mgr: 1,
},
{
name: 'vp2',
id:3,
mgr: 1,
},
{
name: 'mgr',
id:4,
mgr: 2,
},
];
function displayOrg(data) {
let org = {};
for(let i = 0; i < data.length; i++) {
let current = data[i];
for(let key in current){
if(org[key] !== current.id || current.mgr){
org[current.id] = []
}
}
for(let key in org){
console.log(current.mgr);
console.log(org[key])
if(current.mgr === org[key]){
console.log("THIS HAPPEN");
org[key].push(current.name);
}
}
}
return org;
}
displayOrg(data);
expected resulted: { '1': [vp1,vp2], '2': [mgr], '3': [], '4': [] }
looks pretty straight forward:
function getMngd(data, mngrId){
return data.filter(emp => emp.mgr === mngrId).map(emp => emp.name)
}
data.reduce((p,c)=>{
const {id} = c;
p[id] = getMngd(data, id);
return p;
},{})

Categories

Resources