Hi so what iam trying to achieve is basically is simple.Iam try to get only the object key's value from the given array
so this is my example array
[{'aaa': '11','text':'hello'},{'aaa': '12','text':'bye'}]
iam expecting a output of something like this
[11,12]
where iam getting the data of the aaa key only
This will do what you want, but the order could well change between different javascript implementations
const input = [{'aaa': '11','text':'hello'},{'bbb': '12','text':'bye'}]
const output = input.map(x => Object.values(x)[0]);
console.log(output)
I note you updated the quesrtion to have both the same first key - if you're looking for aaa value from all elements this is much simpler
const input = [{'aaa': '11','text':'hello'},{'aaa': '12','text':'bye'}]
const output = input.map(x => x.aaa);
console.log(output)
const o = [{'aaa': '11','text':'hello'},{'aaa': '12','text':'bye'}]
const filtered = o.map(i => +i.aaa)
console.log(filtered)
The JSON path if you convert this into a JavaScript Object Notation format (as JSON).
0.aaa = 11
1.bbb = 12
Related
I am trying to dynamically assign data to a variable based on object array values.
I am going to present a simplified data structure:
const data = [{"age":25,"name":"Michael"},{"age":20,"name":"Lara"}]
const data2 = [{"age":26,"name":"Sarah"},{"age":21,"name":"David"}]
I want to assign values to variables. For example, I know this works:
const arr = 'data'
const zero = '0'
const a = 'age'
const test = `${data[zero][a]}`
console.log(test) // returns 25
But can I assign it dynamically(maybe nested template literal)?
const test = `${arr[zero][a]}`
console.log(test) // does not work, because arr is a string
const test = `${${arr}[zero][a]}`
console.log(test) // does not work
Is there any way to achieve this?
Thank you in advance!
Edit:
I overthought the solution(tried to be fancy with template literals).
To solve it, thanks to the input from ggorlen I changed the way my data was stored. That way, it was way easier to access the data dynamically. The solution was fairly similar to the answer from Sowmen Rahman.
I was trying too hard to think about solving a problem in a specific way, when a different approach was more sensible!
Something like this won't be possible in the way you're suggesting. Strings can't be dynamically converted to variable names by itself, however if you stored your variables in a dictionary or map object, you can use the subscript operator [] to achieve the task.
const data = [{"age":25,"name":"Michael"},{"age":20,"name":"Lara"}]
const data2 = [{"age":26,"name":"Sarah"},{"age":21,"name":"David"}]
const rootObject = {
data: data,
data2: data2
}
const arr = 'data'
const zero = '0'
const a = 'age'
const test = `${rootObject[arr][zero][a]}`
console.log(test) // outputs 25
I'm having an input in the form of a string variable msg.payload as given below.
Hi Team,
Below are the details of for the given source platform.
name=abc
status=Active
company=Discovery
FromDate=6/05/2020
ToDate=20/05/2020
Please do the needful ASAP
Thanks & Regards,
xyz
I want to take only the
name=abc
status=Active
company=Discovery
FromDate=6/05/2020
ToDate=20/05/2020
ignore the rest and then convert it into JSON using JavaScript like
{"name":"abc", "status":"Active","company":"ABCD" ,"FromDate":"6/05/2020","ToDate":"20/05/2020"}
How can I accomplish it? All the data in the input will be of the form key=value.
You can take advantage of several built-in JavaScript string and array functions.
Convert input to an array of lines with String.prototype.split():
const lines = input.split('\n');
Filter out lines that don't contain an equals sign with Array.prototype.filter():
const kvPairs = lines.filter(line => line.includes('='));
Use Array.prototype.forEach() and String.prototype.split() to load the object with key-value properties:
let object = {};
kvPairs.forEach(line => {
[key, val] = line.split('=');
object[key] = val;
});
Putting it all together:
const input = 'Hi Team,\nBelow are the details of for the given source platform.\nname=abc\nstatus=Active\ncompany=Discovery\nFromDate=6/05/2020\nToDate=20/05/2020\nPlease do the needful ASAP\nThanks & Regards,\nxyz';
const lines = input.split('\n');
const kvPairs = lines.filter(line => line.includes('='));
let object = {};
kvPairs.forEach(line => {
[key, val] = line.split('=');
object[key] = val;
});
console.log('object:', object);
I have a string as "a.b.c.d:50" so i want to form an array with the above string as t[a][b][c][d]=50. so i have tried to split the code and form but this length of n values will generate dynamically. please let me know how we can achieve this.for fixed arrays i tried as below but not able to make this as for n number of arrays.
var str1="a.b.c.d:50";
var str=str1.split(":");
var dump=str[0].split(".");
t[dump[0]][dump[1]][dump[2]][dump[3]]=dump[4]
then result will be t[a][b][c][d]=50
You could take the JSON string, parse it and iterate all key/value pairs for a nested structure by saving the last key and crate new objects if not exist and assign the vlaue with the last property.
function setValue(object, path, value) {
var last = path.pop();
path.reduce((o, k) => o[k] = o[k] || {}, object)[last] = value;
}
var json = '{"subscriber.userTier.segment": "Red"}',
object = {};
Object
.entries(JSON.parse(json))
.forEach(([keys, value]) => setValue(object, keys.split('.'), value));
console.log(object);
Are you able to use ES6? This is something I just wrote quickly
var t = {a:{b:{c:{d:0}}}};
var str = "a.b.c.d:50"
var [chain, value] = str.split(':')
var parts = chain.split('.');
parts.slice(0, -1).reduce((c, v) => c[v], t)[parts[parts.length - 1]] = value;
console.log(t.a.b.c.d); // logs "50"
It works, however there is no error handling. If t['a']['b'] is undefined for example then you will get an uncaught TypeError, also if the string is in the incorrect format etc, it won't work.
At it's heart it uses reduce on the array ['a', 'b', 'c']. We pass t as the initial value for the reducer and then for each item in the array it does currentValue = currentValue[nextPart]. This will get you the object c, we then look at the last value in the parts array and set that property currentValue[lastPart] = value
That's a brief overview, hopefully you understand the rest of what's going on. If not feel free to ask :)
Quick and Dirty way of converting a string to a JSON object, if the string is constructed as a valid object.
var str = "a.b.c.d:50";
str = str.replace(/([a-z]){1}/gi, "\"$1\"");
str.split(".").forEach(function (value) {
str = str.replace(/\.(.*?)$/, ":{$1}");
});
var ar = JSON.parse("{"+str+"}");
console.log(ar);
I'm looking to convert a nested array of the type string to type float, or alternatively parsing it from a text file. Format is something along the lines of this [45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]
The first step would be to create valid JSON from your string.
If your input will always follow the schema you showed us, you could just prepend and append brackets to the string. This is not a pretty solution though. You should first check if you can get valid JSON in the first place.
A solution could look like this, provided that the input string will always follow the format of "[float, float], [float, float]":
const input = "[45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]";
// Add brackets in order to have valid JSON.
const arrayString = "[" + input + "]";
// Parse the string into an object.
const parsedArray = JSON.parse(arrayString);
// Flatten the nested array to get a one dimensional array of all values.
var flattenedArrays = [].concat.apply([], parsedArray);
// Do something with your values.
flattenedArrays.forEach(floatValue => console.log(floatValue));
You can use JSON.parse, if your numbers are actually numbers in a JSON (serialized without quotes).
let test = "[[3, 4.2], [5, 6]]";
let test2 = JSON.parse(test);
console.log(test2);
Otherwise you can simply convert your array of array of strings to array of array of numbers using + and some array mapping. :
let test = [["3", "4.2"], ["5", "6"]];
let test2 = test.map((x) => x.map((y) => +y));
console.log(test2);
Of course, you can combine both solutions if for some reason you don't control the input and have a JSON containing strings.
This thread shows you how to loop through an array of strings to convert it to an array of floats.
i hope this will work..
var input = [[45.68395, 32.98629],[23.6777, 43.96555],[43.66679, 78.9648]]
var output = [];
input.forEach(o => {
o.forEach(s => parseFloat(s))
output.push(o);
})
console.log(output);
I have a string like this (this is a result i got from a rest API, however it's not a Json array, it is a string):
[Alex:1, Rose:12, Howdie:72, Lina:1, Emily:1, Pac:15, Virus:1, Love:18, Brie:11]
Now what I need is to return the name with highest value (in this example this would be the name Howdie). I am thinking of building a function to look for the highest number and return that name. However, I am not sure if there is any way to do this with JavaScript.
If its a string like this:
const input = "[Alex:1, Rose:12, Howdie:72, Lina:1, Emily:1, Pac:15, Virus:1, Love:18, Brie:11]";
We firstly need to import it to a valid js array:
const parsed = input
.replace("[","")
.replace("]","")
.split(", ") //get key value pairs
.map(pair => pair.split(":"));//get 2d array
So now we could sort the parsed after the value descending:
parsed.sort(( [nameA,valueA], [nameB,valueB] ) =>
valueB - valueA
);
To get the biggest one ( the first one ):
const result = parsed[0];
//key and value:
const key = result[0], value = result[1];
//OR both at once
const [key,value] = parsed[0];
the upper code is ES6, you may use var instead of const and a regular function instead of => if you want to support old browsers
If you dont think that the upper code works, click here ;)