Adding data to existing object mapping a contanst key/value - javascript

In my first function, I am getting a few pieces of information and pushing them to my object.
autoArry.push({
id: countTxns,
txnID: txnID,
account: buyersAccount,
data1: '',
data2: '',
data3: ''
});
At this point, I dont have the information from data1, data2, or data3 but I created them in the object anyway.
Later in my script, I want to be able to fill in those data values when i collect it throughout other functions.
The one thing that I will have that is the same in every function is the txnID.
I assume I will have to Map that somehow and then add additional data that way.
Would anyone be able to explain how I could do this?
Thanks Much

Iterate and check for a match :
function otherFunction(txnID) {
for (var i=0; i<autoArray.length; i++) {
if (autoArray[i].txnID == txnID) {
autoArray[i].data1 = 'something 1';
autoArray[i].data2 = 'something 2';
autoArray[i].data3 = 'something 3';
}
}
}

Related

From single array convert to an array of object with keys coming from a JSON response -JAVASCRIPT-

I am receiving a json response from an API call. I need to store its keys, and create an array of an object. I am intending to this array of an object is created dynamically no matter the keys of the response.
I've already got the keys like this:
const json_getAllKeys = data => {
const keys = data.reduce((keys, obj) => (
keys.concat(Object.keys(obj).filter(key => (
keys.indexOf(key) === -1))
)
), [])
return keys
}
That returned an array (using a sample json):
['name','username', 'email']
But I am trying to use that array to create an array of object that looks like this one
[
{
name: "name",
username: "username",
email: "Email",
}
];
I've been trying mapping the array, but got multiple objects because of the loop, and I need a single one to make it work.
keys.map(i=>({i:i}))
[
{ i: 'id' },
{ i: 'name' },
{ i: 'username' },
{ i: 'email' }
]
Any hint would be useful!
Thanks in advance :D
What you're looking for is Object.fromEntries, which is ECMA2019, I believe, so available in Node >=14 and will be provided as a polyfill if you employ babel.
I can't quite discern what your reduce should produce, but given the sample input, I would write
const input = ['name','username', 'email'];
const result = Object.fromEntries(input.map(name => ([name, name])));
// result == { name: 'name', username: 'username', email: 'email' }
You're definitely on the right track. One thing to remember is the map function will return the SAME number of output as input. So in your example, an array of 3 returns an array of 3 items.
For this reason, map alone is not going to give you what you want. You may be able to map => reduce it. However, here is a way using forEach instead. This isn't a strictly functional programming style solution, but is pretty straight forward and depending on use case, probably good enough.
let keys = ['name','username', 'email'] //you have this array
const obj = {}; // empty object to hold result
keys.forEach(i => {
obj[i] = i; // set the object as you want
})
console.log(obj); // log out the mutated object
// { name: 'name', username: 'username', email: 'email' }

Iterating through the RowPacketData ( result return from mysql query in node js)

Case is that I have code to get Product name and Image path from MySQL, so I get RowPacketData in return of query which is like :
[ RowDataPacket {
Id: 1,
Heading: 'Banner 1',
Banner_Description: 'This is Banner 1 Description',
Image_Name: '1596019684532_command3.png' },
RowDataPacket {
Id: 2,
Heading: 'Banner 2',
Banner_Description: 'This is Banner 1 Description',
Image_Name: '1596019684538_command4.png' } ]
Now I want to append the 'Image_Name' to something like 'var/www/html/Image_Name' and send it to front end. What is best approach to implement this logic for each Image_Name.
Note : I don't want to go in loops.
Presumably you want to send a JSON array to your front end. So you need some code to prepend the path to each Image_Name element. Maybe something like this will work, given your array is in input.
function prependPath (input, path = 'var/www/html/') {
for (let i=0; i<input.length; i++) {
const item = input[i]
item.Image_Name = path + item.Image_Name
}
return input
Or you could do this to be a bit more concise.
function prependPath (input, path = 'var/www/html/') {
input.forEach (item => item.Image_Name = path + item.Image_Name)
}
return input
}
Then call the function with something like res.json(prependPath (input)) (if you're using Express).

Delete operator not working in Javascript

This is a function that removes sensitive information from a JSON object before it gets returned to the client. The data that's being passed into the function would either be a JSON object or an array of JSON objects. Why would this function not work?
I know that there are other solutions to the problem, but this is annoying my brain.
I have logged plenty of information in this function and even though JavaScript is asynchronous the functions are running in the order that they should - the recursion is finishing before the final return statement is hit.
The issue right now is that even though everything seems to be working and the delete operator is returning true, the attributes being deleted are still present when the function finally returns.
Example data which is being fetched from MongoDB:
[
{
'id': '1',
'name': 'John',
'password': 'test123',
'emailAddress': 'john#example.com',
'emailAddressVerificationCode': 'A897D'
},
{
'id': '2',
'name': 'Andrew',
'password': 'test123',
'emailAddress': 'andrew#example.com',
'emailAddressVerificationCode': '90H8D'
},
{
'id': '3',
'name': 'Matthew',
'password': 'test123',
'emailAddress': 'matthew#example.com',
'emailAddressVerificationCode': '56C7C'
}
]
Any thoughts would be appreciated.
UserService.cleanJSON = (data) => {
if (Array.isArray(data)) {
for (let i = 0; i < data.length; i++){
data[i] = UserService.cleanJSON(data[i]);
}
} else {
if (data.password) delete data.password;
if (data.emailAddressVerficationCode) delete data.emailAddressVerficationCode;
if (data.mobileNumberVerificationCode) delete data.mobileNumberVerificationCode;
if (data.accountType) delete data.accountType;
}
return data;
};
You are probably using Mongoose or any other ODM, right?
If so, you have to know that you can not change the results unless you call the method .lean() (http://mongoosejs.com/docs/api.html#query_Query-lean).
Mongoose keeps the model safe from any modifications unless you detach the result.
Remove the comma after the last curly bracket in your JSON.

How to get a value from an array by name instead of key-number

I've created an object and added an asset b345 with some properties in it:
asset = [];
asset.push({'b345' : { 'prop1':'value 1', 'prop2': null}});
I want to push some more assets later, dynamicaly into the same asset-object. So that the asset object holds all assets generated in the code.
Later on in my code I want to retrieve the array associated with one of the entries via the unique identifier b345. But that seems not to work.
asset['b345'];
But that results in an undefined. But If I try to get the data via asset[0] It returns the right object.
How could I arrange this container object asset so that I can
1- easliy add new objects
2- retrieve the object via the identifier?
ps: I found this: https://npmjs.org/package/hashtable but it is only usefull for large storage; and it says it can be done through objects only. But I can't find how it works :(
If you have no need to iterate through your list of objects in some consistent order, then you probably shouldn't make an array in the first place; just make an object:
var asset = {};
asset['b345'] = { 'prop1':'value 1', 'prop2': null};
If you do need to have both array behavior and key-lookup, an efficient way to do it would be to make an array and an object:
var assets = {
list: []
, map: {}
, push: function(key, value) {
map[key] = value;
list.push({ key: value });
}
};
Then:
assets.push('b345', { 'prop1': 'value 1', 'prop2': null });
Subsequently assets.list[0] will be { b345: { prop1: 'value 1', prop2: null }} and assets.map['b345'] will be {prop1: 'value 1', 'prop2': null}.
You'd want to make it a little more sophisticated to deal with updates properly, but that's the basic pattern.
Instead of using an array you use an object
asset = {};
asset['b345'] = { 'prop1':'value 1', 'prop2': null};
then asset['b345'] will give you { 'prop1':'value 1', 'prop2': null}
There's many way to do this. To simply fix this problem:
var asset = new Object; // new object
asset['b345'] = {'prop1':'value 1', 'prop2': null}; // an object property = new object (wrapped in {})
Another way, is:
asset = {'b345' : { 'prop1':'value 1', 'prop2': null}};

Only add if not already in place

Here's my data structure:
var data = [
{ id: '1924', info: 'boo' },
{ id: '1967', info: 'foo' }
];
The id value should be unique, but the info may not be unique. How would I add new data into the data hash only if the id of the new data is unique?
Is the only way to iterate over the whole hash and see if there is such an id already in place?
data.push({ id: '1967', info: 'goo-goo' }); //should not be added
data.push({ id: '1963', info: 'goo-goo' }); //should be added
If you can change your data structure, it can be done with less code:
var data = {
'1924': {'info': 'goo-goo'},
'1967': {'info': 'boo-boo'}
};
function add(obj, id, data) {
if (obj[id] === undefined) { // if you have fear about the prototype chain being poisoned
// add in a hasOwnProperty
obj[id] = data;
}
}
This will also have the benefit of being a lot faster to access (if you have the ID).
Ivo, the problem with your solution is that I also keep track of the index of the info currently being displayed. The index of { id: '1967', info: 'foo' } would be 1 in that data hash, so I can reference it by data[1] if needed.

Categories

Resources