Convert object with arrays to new objects and attach it - javascript

I will this typescript object convert:
api:{
accessToken:[user1::aaaaa,user2::bbbbb],
accessSecret:[user1:aaaaa,userb::bbbbb]
}
i will split the string inside the arrays by :: sign.
Finish object should look like this
api:{
accessToken:[user1::aaaaa,user2::bbbbb],
accessSecret:[user1:aaaaa,userb::bbbbb],
user1_access:aaaaa,
user2_access:bbbbb,
user1_secret:aaaaa,
user2_secret:bbbbb
}
What is the best solution without compile errors in typescript, please Help.

Here is a sample which gives you an idea of how to go about it,
const api = {
accessToken:["user1::aaaaa","user2::bbbbb"],
accessSecret:["user1::xxxx","user2::yyyy"]
};
const newApiObj: any = {};
const accessTokenvalues = api.accessToken.map(x => x.split("::")) ?? [];
for(const item of accessTokenvalues){
newApiObj[item[0] + '_access'] = item[1];
}
const accessSecretvalues = api.accessSecret.map(x => x.split("::")) ?? [];
for(const item of accessSecretvalues){
newApiObj[item[0] + '_secret'] = item[1];
}
console.log(newApiObj);

Related

how to convert {obj:"{objects}"} into array with json object inside it

I had % in my cookie and I found following code for it and got the data below after implying that code
var cookies = (document.cookie);
var output = {};
cookies.split(/\s*;\s*/).forEach(function (pair) {
pair = pair.split(/\s*=\s*/);
var name = decodeURIComponent(pair[0]);
var value = decodeURIComponent(pair.splice(1).join('='));
output[name] = value;
});
console.log(output);
The data console is down below;
{"objName":"[{"key":1,"key2":"value 123","key3":"value123"},{"key":1,"key2":"value 123","key3":"value123"}]"}
I have the data as shown above, What I want is to objName into array and remove "" from in front of [] array barckets
objName=[{"key":1,"key2":"value 123","key3":"value123"},{"key":1,"key2":"value 123","key3":"value123"}]
As far as I understand, you are trying to get cookie values, you can try this code and handle the returned array as you need. You can try this solution and let me know if it works.
var cookies = document.cookie.split(';').reduce(
(cookies, cookie) => {
const [name, val] = cookie.split('=').map(c => c.trim());
cookies[name] = val;
return cookies;
}, {});
console.log(cookies);

Returning an entire item in an arrray containing a specific value

I'm trying to get an item in array which contains a specific value.
Let's say I have an array
var arr = ["boat.gif", "goat.png", "moat.jpg"];
And I have a variable var imageName = "boat"
Since I do not know the file extension of imageName, I need a way to run it through my array and get "boat.gif" as the output.
I tried this with regular expressions
let filesString = arr.join(" ");
let regExName = new RegExp(imageName, "i");
let fileName = regExName.exec(files­String),
file = fileName.input.subst­r(fileName.index, 5);
It works but I'm hoping there's a better way
I hope this makes sense
Might be easier to filter by .includes or .startsWith instead:
var arr = ["boat.gif", "goat.png", "moat.jpg"];
var imageName = "boat";
const found = arr.find(str => str.includes(imageName));
console.log(found);
or
var arr = ["boat.gif", "goat.png", "moat.jpg"];
var imageName = "boat";
const found = arr.find(str => str.startsWith(imageName));
console.log(found);
If there might be other files in the directory which start with the same word (like boats.gif), then construct a regular expression like you're doing, but lookahead for a .:
var arr = ["boat.gif", "goat.png", "moat.jpg"];
var imageName = "boat";
const pattern = new RegExp(imageName + '(?=\.)');
const found = arr.find(str => pattern.test(str));
console.log(found);

how to choose a random item from arrays nested in an object

I'm trying a project that will choose a random answer out of one of the 3 nested arrays in my object. My goal is to know afterwards out of which array the answer came, so I can use that to know what the new sentence will be.
The example below works with 1 array, but i want to know if the answer is a good, bad or doubt answer, hence why i put it in an object.
EDIT: code below gives me a random property in my object, but i need to go one step deeper. The comment next to it is what i tried but it gives me undefined.
const randomAnswers = {
goodAnswers: ['yes','Absolutely','certainly',"I'm sure",'HELL YES'],
maybes: ['maybe','probably','perhaps',"honestly man, i really don't
know this one"],
badAnswers: ['LOL NO','no way man','maybe',"forget it",'HELL no','Are
you serious?']
};
{
const init = () => {
console.log("initiated");
let answer = document.querySelector('.answer');
answer.style.opacity = 0;
setTimeout(fixSentence,3000);
//fixSentence();
}
const fixSentence = () => {
let a = document.querySelector('.answer');
let think = document.querySelector('.think');
console.log('shown');
console.log(a.textContent);
let randomAnswer = randomAnswers[Math.floor(Math.random()*randomAnswers.length)];
var randomProperty = function (obj) {
var keys = Object.keys(obj)
let random = obj[keys[ keys.length * Math.random() << 0]];
return random/*[Math.floor(Math.random()*randomAnswers.length)]*/;
};
console.log(randomProperty(randomAnswers))
let splittedSentence = a.textContent.split(" ");
console.log(splittedSentence);
a.textContent = `${randomAnswer}`;
a.style.opacity = 1;
think.style.opacity = 0;
}
init();
}
the output of console.log(randomAnswer) is obviously undefined right now, but I can't figure out how to choose a random item out of one of the three arrays in the object.
You could do something like this:
const randomAnswers = {
goodAnswers: ['yes','Absolutely','certainly',"I'm sure",'HELL YES'],
maybes: ['maybe','probably','perhaps',"honestly man, i really don't know this one"],
badAnswers: ['LOL NO','no way man','maybe',"forget it",'HELL no','Are you serious?']
};
const randomNumber = function(subject) {
return Math.floor(Math.random()*subject.length);
}
const types = Object.keys(randomAnswers);
const randomTypeNumber = randomNumber(types);
const randomType = types[randomTypeNumber];
const randomAnswerNumber = randomNumber(randomAnswers[randomType]);
const randomAnswer = randomAnswers[randomType][randomAnswerNumber];
console.log( { randomType, randomAnswer } );
You pick a random key from the object, and then pick a random element from that array by using Object.keys(randomAnswers).length and subsequently that array length for the random numbers.

Javascript Appending to 2-D Array

I am trying to append an array to an array. I am expecting the output to be something like:
[[Dep,POR],[14073,99.25],[14072,0.06]]
But I am getting:
Dep,POR,14073,99.25,14072,0.06
Here's what I have so far:
function get_historical() {
var well = document.getElementById('wellSelect');
var selected_well = well.options[well.selectedIndex].value;
var hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
hist_por = ['Dep','POR'];
for (var item in hist_json_obj) {
if (hist_json_obj.hasOwnProperty(item)) {
var dep = hist_json_obj[item].dep;
var por = hist_json_obj[item].por;
var arr_por = [dep, parseFloat(por)];
hist_por.push(arr_por);
}
}
document.write(hist_por);
}
When you initialize hist_por, you want that to be a 2-D array whereas you currently have just a single array. So you would want to change its instantiation to:
hist_por = [['Dep','POR']]; // [[ ... ]] instead of [ ... ]
Also per #justrusty's answer, you need to JSON.stringify(hist_por) when you pass it to document.write(). This is the more important piece so his answer should be accepted.
So the whole code block would become:
function get_historical() {
var well = document.getElementById('wellSelect');
var selected_well = well.options[well.selectedIndex].value;
var hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
hist_por = [['Dep','POR']];
for (var item in hist_json_obj) {
if (hist_json_obj.hasOwnProperty(item)) {
var dep = hist_json_obj[item].dep;
var por = hist_json_obj[item].por;
var arr_rop = [dep, parseFloat(por)];
hist_por.push(arr_por);
}
}
document.write(JSON.stringify(hist_por));
}
This may help you https://codepen.io/anon/pen/xQLzXx
var arr = ['foo','bar'];
var arr2 = ['baz', 'boo']
arr.push(arr2);
console.log(arr);
document.write(arr);
document.write("<br>");
document.write(JSON.stringify(arr));
It's basically just the way it writes it to document. If you log it in console you'll see the array appended. Or if you JSON.stringify() first it will show as you expect.
My advice is ALWAYS console.log() so you can see exactly how the data is structured
The others have already pointed out what the problem is (+ there's a typo in one of your variable names - arr_rop vs arr_por). Here's an ES6 version that will break in older browsers, for learning purposes:
function get_historical() {
const well = document.getElementById('wellSelect');
const selected_well = well.options[well.selectedIndex].value;
const hist_json_obj = JSON.parse(Get("/get_historical/" + selected_well));
const hist_por = Object.values(hist_json_obj).reduce(
(arr, item) => [...arr, [item.dep, +item.por]],
[["Dep", "POR"]]
);
document.write(JSON.stringify(hist_por));
}

Adding a property to an array of objects from another array

I have an array like this with names and address:
BTDevices = [
{name:"n1", address:"add1"},
{name:"n2", address:"add2"},
{name:"n3", address:"add3"}]
And another array with alias and address:
EqAlias = [
{btAlias:"a1", address:"add0"},
{btAlias:"a2", address:"add2"},
{btAlias:"a3", address:"add9"}]
I want to add btAlias property to all objects in BTDevices and set the value only if the address are the same, for example in this case I want the following result:
BTDevices:
name:"n1", address:"add1", btAlias:""
name:"n2", address:"add2", btAlias:"a2"
name:"n3", address:"add3", btAlias:""
My first solution was adding btAlias property using forEach and then using two for loops:
// Add Alias
this.BTDevices.forEach(function(obj) { obj.btAlias = "" });
// Set Alias
for (let m = 0; m < this.EqAlias.length; m ++)
{
for (let n = 0; n < this.BTDevices.length; n++)
{
if (this.BTDevices[n].address == this.EqAlias[m].address)
this.BTDevices[n].btAlias = this.EqAlias[m].btAlias;
}
}
Is there a better way to do the same? I guess using forEach
Using forEach instead of for will just replace the two for loop with forEach. We could argue on which is the best between for and forEach but i don't think there's a good answer. In modern javascript you can also use the for of loop.
Your algorithm is the simpliest and it will work.
But, if you want to address some performances issues, you should want to know that your algorithm is also the slowest (O(n²) complexity)
Another way to do that is to store items of BTDevices in a map to find them faster. Example:
let map = new Map();
BTDevices.forEach(e => map.set(e.address, e));
EqAlias.forEach(e => {
let device = map.get(e.address);
if (device) {
device.btAlias = e.btAlias;
}
});
The only advantage of this code is that looking for an item in a Map is faster (between O(1) and O(n), it depends of Map implementation). But you won't see any differences unless you try to manipulate some very big arrays.
You can use map and find
Use map to loop the array and create a new array.
Use find to check if a string is in an array.
let BTDevices = [{name:"n1", address:"add1"},{name:"n2", address:"add2"},{name:"n3", address:"add3"}];
let EqAlias = [{btAlias:"a1", address:"add0"},{btAlias:"a2", address:"add2"},{btAlias:"a3", address:"add9"}];
let result = BTDevices.map( v => {
v.btAlias = ( EqAlias.find( e => e.address == v.address ) || { btAlias:"" } ).btAlias;
return v;
});
console.log( result );
Please check doc: .map, .find
You could also do something like this.
var BTDevices = [{name:"n1", address:"add1"},{name:"n2", address:"add2"},{name:"n3", address:"add3"}];
var EqAlias = [{btAlias:"a1", address:"add0"},{btAlias:"a2", address:"add2"},{btAlias:"a3", address:"add9"}];
var EqAliasAdd = EqAlias.map((e)=>e.address);
var BTDevicesAdd = BTDevices.map((e)=>e.address);
BTDevicesAdd.map(function(i,k) {
BTDevices[k].btAlias = "";
if(EqAliasAdd.indexOf(i) >= 0)
BTDevices[k].btAlias = EqAlias[k].btAlias;
});
console.log(BTDevices);

Categories

Resources