I am fetching data from a text file and need help in making the information into an object..
Array:
['celestine,timmy,celestinetimmy93#gmail.com,repeat 124\narun,mohan,reach#gmail.com,repeat 124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n' ]
I need the values till \n in one object
expected result:
[{'celestine,timmy,celestinetimmy93#gmail.com,repeat 124}
{arun,mohan,reach#gmail.com,repeat 124213}
{jalal,muhammed,jallu#gmail.com,rave1231212321}
{vineeth,mohan,get,rave1231212321} ]
you can do in this way.
after applying splitting by '\n'
['celestine,timmy,celestinetimmy93#gmail.com,repeat
124\narun,mohan,reach#gmail.com,repeat
124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n'
]
you will get single one dimensional array.
["celestine,timmy,celestinetimmy93#gmail.com,repeat 124", "arun,mohan,reach#gmail.com,repeat 124213", "jobi,mec,mec#gmail.com,rave", "jalal,muhammed,jallu#gmail.com,rave1231212321", "vineeth,mohan,get,rave1231212321", ""]
Then looping it to get each individual record.
JS :
var test = ['celestine,timmy,celestinetimmy93#gmail.com,repeat 124\narun,mohan,reach#gmail.com,repeat 124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n' ]
var arrString = [];
test.forEach(function(val,key){
arrString = val.split('\n')
});
console.log(arrString);
arrString.forEach(function(val,key){
console.log(val.split(','));
})
In order to create an object, you'll need to format the string inside the curly braces as a dictionary of key value pairs. I am not sure what the keys or values are in your case. However if I assume that the key is "key" and the value is the text then:
var txt = 'celestine,timmy,celestinetimmy93#gmail.com,repeat 124\narun,mohan,reach#gmail.com,repeat 124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n';
// Use trim, to remove the trailing whitespace, in your case a '\n'
// Use split to convert the text into an array of elements
var arr = txt.trim().split('\n');
// Use the map function to map each string to an object
var objects = arr.map(function(element) {
return { key: element};
});
Here is the output:
objects = [ { key: 'celestine,timmy,celestinetimmy93#gmail.com,repeat 124' },
{ key: 'arun,mohan,reach#gmail.com,repeat 124213' },
{ key: 'jobi,mec,mec#gmail.com,rave' },
{ key: 'jalal,muhammed,jallu#gmail.com,rave1231212321' },
{ key: 'vineeth,mohan,get,rave1231212321' } ]
try this idea.
var x = "celestine,timmy,celestinetimmy93#gmail.com,repeat 124\narun,mohan,reach#gmail.com,repeat 124213\njobi,mec,mec#gmail.com,rave\njalal,muhammed,jallu#gmail.com,rave1231212321\nvineeth,mohan,get,rave1231212321\n";
var y = x.split("\n");
implement the remaining part. convert the array of arrays into array of objects using loops
Related
SO I have array1 with values ["folderid":"DTSZ", "folderid":"IEACF6FVGG", "folderid":"IEACKQC6A"] and another array 2 with values ["title":"firsttitle", "title":"second","title":"thirdtitle"]
Now lets say using javascript i want to save it as json object.
[
{"folderid":"DTSZ","title":"firsttitle"},
{"folderid":"IEACF6FVGG", "title":"second"},
{"folderid":"IEACKQC6A", "title":"thirdtitle"}
]
I trying looping and concat but didn't work properly.
array1= ["folderid":"DTSZ", "folderid":"IEACF6FVGG", "folderid":"IEACKQC6A"] ;
array2 = ["title":"firsttitle", "title":"second","title":"thirdtitle"];
Get array with json objects
[
{"folderid":"DTSZ","title":"firsttitle"},
{"folderid":"IEACF6FVGG", "title":"second"},
{"folderid":"IEACKQC6A", "title":"thirdtitle"}
]
In JavaScript an array has just values, in you examples the array is invalid since you try to add direct key: values elements . i.e.
["folderid":"DTSZ"] // invalid !! (notice semicolon)
["folderid", "DTSZ"] // VALID (notice comma)
If you want to translate to a valid array and then to an object, you could use something like entries, which are array of arrays.
Let's take your first example and convert it to entries:
const arr1 = [["folderid", "DTSZ"], ["folderid", "IEACF6FVGG"], ["folderid","IEACKQC6A"]]
Then to convert this to object you can use Object.fromEntries just like this:
const obj1 = Object.fromEntries(entries);
So, focus first to convert your initial invalid arrays to entries, and then the job is done!
use the following code.
var a = [{ "folderid": "DTSZ" }, { "folderid": "IEACF6FVGG" }, { "folderid": "IEACKQC6A" }]
var b = [{ "title": "firsttitle" }, { "title": "second" }, { "title": "thirdtitle" }]
var newObject = a.map((o, index) => {
const temp = Object.assign(o, b[index]);
return temp;
});
console.log('output ---- ', newObject)
I want to convert a JSON string into a set of array containing the values from the JSON. after json.stringify(jsonmybe) and alert it display [{"role":"noi_user"},{"role":"bert_user"}] (which i saw as a JSON). I want to get the noi_user and bert_user and set them into a javascript array. something like ['noi_user','bert_user'] with quotes in each value.
I did the var stringy = json.parse() and the alert showing [object Object]. and further add this lines
for (var i = 0; i < stringy.length; i++) {
arr.push(stringy[i]['role']);}
and the arr I get was a value with comma when in alert but the comma missing as i display them in the text field and it becomes a long string like noi_userbert_user
What I really want is from [{"role":"noi_user"},{"role":"bert_user"}] to ['noi_user','bert_user']
Use JSON.parse and then reduce to get what you want,
var s = `[{"role":"noi_user"},{"role":"bert_user"}]`
var arr = []
try {
arr = JSON.parse(s).reduce((acc, val)=>[...acc, val.role], [])
} catch (e){
console.log("Invalid json")
}
console.log(arr)
Is this what you are loking for ? You can map on your array and just extract the role attribute of each datum.
const jsonString = ...
const data = JSON.parse(jsonString).map(data => data.role);
console.log(JSON.stringify(data, null, 2));
JSON uses double quotes to delimit strings and field names.
So you have a JSON string like
'[{"role":"noi_user"},{"role":"bert_user"}]'
You want to convert it to an object, then extract values of "role" fields of each element, put them all into an array.
Your example json string contains an array of user objects within "role" fields. Following code takes this list, loops through each user object and puts role's of each object into a separate array roleList.
var jsonStr = '[{"role":"noi_user"},{"role":"bert_user"}]';
var userObjList = JSON.parse(jsonStr);
var roleList = [];
userObjList.forEach(userObj => {
roleList.push(userObj.role);
});
console.log(roleList);
You could make a custom function to produce a sort of array_values in PHP but an indented and 2D level like so:
function array_values_indented (input) {
var tmpArr = []
for (key in input) {
tmpArr.push(input[key]['role']);
}
return tmpArr
}
var object = JSON.parse('[{"role":"noi_user"},{"role":"bert_user"}]');
var result = array_values_indented(object);
console.log(result);
I am querying my db in node and have got the result in the form of an object like this - [ [1234] ].
I want to extract this value and convert it into a string and then pass it onto the client side. I have written the other required code but I am not able to get value from this object. Can anyone help me in getting the value and converting it to string?
Since, the result you've got is a two-dimensional array, you can get the value and convert it into a string (using toString() method) in the following way ...
var result = [ [1234] ];
var string;
result.forEach(function(e) {
string = e.toString();
});
console.log(string);
** this solution will also work if you have multiple results, ie. [ [1234], [5678] ]
You have a nested array, meaning that you have an array inside another array:
[ [1234] ]
// ^-^====^-^
To get the first value of the parent array, use the square brackets: [0]. Remember that indexes start at 0!
If you have val = [[1234]], val[0] gets the enclosed array: [1234]. Then, 1234 is a value in that array (the first value), so you use the square brackets again to get it: val[0][0].
To convert to string, you can use + "" which forces the number to become a string, or the toString() method.
var val = [[1234]];
var str = val[0][0] + "";
// or val[0][0].toString();
console.log(str, typeof str);
You can read more about arrays here.
var response = [ [1234] ];
console.log(response[0][0]);
to extract values from a string array or an array we can use .toString()
Ex:
let names = ["peter","joe","harry"];
let fname = names.toString();
output = peter ,joe,harry
or
let name:string[] = this.customerContacts.map(
res => res.firstname
let fname =name.toString();
Using De-structuring Array concept:
const arr = [[1, 2, 3, 4, 5]];
const [[p, q, r, s, t]] = arr;
console.log(p, q, r, s, t);
Output: 1 2 3 4 5
I got a very common question but with a twist which is the reason for this post:
I want to create a key,value object from a string.
my string looks like this:
01§§foo§§bar§§someLink
(i can change the delimiter symbols to whatever i want, if there should be somehow a very tight solution with a specific symbol)
now, i want a key value object and most questions about this problem already got the datapair in the string,(like "id:01,title:foo") but thats not the case in my problem.
i want to generate something like this:
var modules = [
{"ID":"01", "title":"foo", "description":"bar","link":"someLink"},
//more entries from more strings
];
the reason for the key,value object is, that there are more of these strings which I convert from a database. I want it to be in a key,value object so its easier to work with the data later in my tool.
Thank you in advance
You could use Array#split for the string and an array for the keys.
var string = '01§§foo§§bar§§someLink',
moduleKeys = ["ID", "title", "description", "link"],
object = {};
string.split('§§').forEach(function (a, i) {
object[moduleKeys[i]] = a;
});
console.log(object);
A methode for multiple strings.
function getData(array) {
var moduleKeys = ["ID", "title", "description", "link"];
return array.map(function (string) {
var object = {};
string.split('§§').forEach(function (a, i) {
object[moduleKeys[i]] = a;
});
return object;
});
}
var strings = ['01§§foo§§bar§§someLink', '02§§foo§§bar§§someLink'];
console.log(getData(strings));
I have data being pulled in from various sources, each returning some form of JSON or similar, although, differently formatted each time. I need to get them all into one array, but I can't figure out how to do it.
The first set is an array like this:
[
Object {id="70", type="ab", dateadded="12345678"},
Object {id="85", type="ab", dateadded="87654321"}, ... more items ...
]
The second set is being pulled in from Facebook, and is like this:
[
Object {id="12341234234", created_time="12345678"},
Object {id="567856785678", created_time="87654321"}, ... more items ...
]
So, I need to alter the second set so that it has 'type', and it has 'dateadded' instead of 'created_time', and then I need to get this all into one array so it can be sorted on 'dateadded'.
How can I do this?
Use the first array's push() method:
// for each item in second array
firstArray.push(convert(item));
function convert(obj) {
// Convert obj into format compatible with first array and return it
}
Hope this helps.
Assuming you have actual valid JSON instead of what you quoted above:
var jsonOld = '[{"id":"70","type":"ab","dateadded":"12345678"},{"id":"85","type":"ab","dateadded":"87654321"}]',
jsonNew = '[{"id":"12341234234","created_time":"12345678"},{"id":"567856785678","created_time":"87654321"}]';
Then first parse these values into actual Javascript arrays:
var mainArr = JSON.parse(jsonOld),
newArr = JSON.parse(jsonNew);
(If you already have actual Javascript arrays instead of JSON strings then skip the above step.)
Then just iterate over newArr and change the properties you need changed:
for (var i = 0, il = newArr.length; i < il; i++) {
newArr[i].type = 'ab';
newArr[i].dateadded = newArr[i].created_time;
delete newArr[i].created_time;
}
And concatenate newArr into mainArr:
mainArr = mainArr.concat(newArr);
And sort on dateadded:
mainArr.sort(function(a, b) { return a.dateadded - b.dateadded; });
This will result in:
[{"id":"70","type":"ab","dateadded":"12345678"},
{"id":"12341234234","type":"ab","dateadded":"12345678"},
{"id":"85","type":"ab","dateadded":"87654321"},
{"id":"567856785678","type":"ab","dateadded":"87654321"}]
See example