Convert string to nested array - javascript

I have a string passed from server which was called with AJAX and I have to convert the string into a nested array which will be used to populate on PDF.
For example:
var tableData = "[{ name: 'Bartek', age: 34 },{ name: 'John', age: 27 },{ name:'Elizabeth', age: 30 }]";
and I need to convert into an array in JavaScript which will be like this:
var newTableData = [
{ name: 'Bartek', age: 34 },
{ name: 'John', age: 27 },
{ name: 'Elizabeth', age: 30 }
];
How can I do that?

As pointed out in the comments, the best solution would be to return a valid JSON from the server and to parse it using JSON.parse.
You can use tools like https://jsonlint.com/ or JSV to check that your JSON is valid.
If because of some "real world problem", your servers aren't JSON complaint, you can use a dirty parser like dirty-json or write your own JSON parse.
dirty-json does not require object keys to be quoted, and can handle single-quoted value strings.
var dJSON = require('dirty-json');
dJSON.parse("{ test: 'this is a test'}").then(function (r) {
console.log(JSON.stringify(r));
});
// output: {"test":"this is a test"}
Your last resort, while technically possible and the easiest to implement, is probably your worst choice because of it's dangers. but it would work out of the box: eval.
eval(tableData);
// [ { name: 'Bartek', age: 34 },
// { name: 'John', age: 27 },
// { name: 'Elizabeth', age: 30 } ]

By slightly changing how you return the string from the server you can JSON.parse it
var dataString = '[{"name":"Bartek","age":34},{"name":"John","age":27},{"name":"Elizabeth","age":30}]';
var data = JSON.parse(dataString);
console.log(data);

Use eval() method The completion value of evaluating the given code. If the completion value is empty, undefined is returned:
var tableData = "[{ name: 'Bartek', age: 34 },{ name: 'John', age: 27 },{ name:'Elizabeth', age: 30 }]";
tableData = eval(tableData);
console.log(tableData[0]);

Related

Compare string from array and if duplicate string available then append Incremented number to the duplicate string when creating a record

I need to create a record but I have to check whether in the given list record with same name is available or not if available then append with incremented number. Below is the given list.
let listOfValues = [
{
name: "Peter",
age: 25
},
{
name: "Paul",
age: 35
},
{
name: "Paul-1",
age: 35
},
{
name: "Dom",
age: 28
}
]
And, I am creating a record as below:
let requestBody = {
name: "Paul",
age: 28
}
Now, I want to compare name from requestBody with the given list. Suppose, Paul is already available then it will check if Paul-1 is also available then it should increment with one number like Paul-2. Any help would be appreciated.
Generic Solution
Generate a Regex to check a string that starts with the name in the requestBody.
Filter down the list by searching for the names matching the Regex.
You should split the names on "-" and return the index from the name.
Sort the index list so that the largest index is at the end of the list.
Check length of the list filtered out, if its zero, you can directly push.
If its one you can push the element by appending 1 to the name.
If its greater than one increment the last index and append it to name and push.
Working Fiddle
let listOfValues = [
{ name: "Peter", age: 25 },
{ name: "Paul", age: 35 },
{ name: "Paul-1", age: 35 },
{ name: "Dom", age: 28 }
];
let requestBody = {
name: "Paul",
age: 28
}
const regex = new RegExp('^' + requestBody.name.split('-')[0], 'i');
const existingList = listOfValues.filter((item) => item.name.match(regex)).map((item) => +item.name.split('-')[1]).sort((a, b) => a - b);
if (existingList.length > 0) {
const finalIndex = existingList[existingList.length - 1];
listOfValues.push({ name: finalIndex ? `${requestBody.name.split('-')[0]}-${(finalIndex + 1)}` : `${requestBody.name}-1`, age: requestBody.age });
} else {
listOfValues.push(requestBody);
}
console.log(listOfValues);

Bracket Notation - Accessing numeric keys without quotes

Can you guys give me some technical explanation why we can access object properties using Bracket Notation, without quotes? Using numeric keys, but the JavaScript does convert every key to string, right?
Example:
const people = {
1 : {
name: 'Ronaldo Fenômeno',
age: 42
},
2 : {
name: 'Ayrton Senna',
age: 58
},
test : {
name: 'John Doe',
age: 123
}
}
console.log(people[1]['name']) // why?
console.log(people['2'].name)
console.log(people['test']['name'])

Populating a react-table with an object instead of a list

The documentation for the react-table library (https://github.com/react-tools/react-table#data) states:
"Simply pass the data prop anything that resembles an array or object."
However, the tables are rendered as expected when passing in an array of data, but when passing an object, I get the error:
"Invalid prop data of type object supplied to ReactTable, expected array."
An example data object looks like this:
const data = {
"entry1": {
name: 'Tanner Linsley',
age: 26,
friend: {
name: 'Jason Maurer',
age: 23,
}
}, "entry2": {
name: 'aTanner Linsley',
age: 26,
friend: {
name: 'aJason Maurer',
age: 23,
}
} };
Is this a problem with the structure of my object, or does it simply mean the library does not support the population via objects in this way?
Note: I prefer to maintain this data structure (which will become huge) as an object (dictionary) instead of an array so I can efficiently access elements by key for another use (outside of react-table).
The react-table library would expect an input like that:
const data = [{
name: 'Tanner Linsley',
age: 26,
friend: {
name: 'Jason Maurer',
age: 23,
}
},{
name: 'aTanner Linsley',
age: 26,
friend: {
name: 'aJason Maurer',
age: 23,
}
}];
I prefer to maintain this data structure
Is there any particular reason to that? However, if you really want to do it like that, you could apply the Object.values(...) (MDN Source) method to your data before passing it to the component. In that case you can manage it as you desire and the component will get the right data structure.
const convertedObject = Object.values(data);
But keep in mind that in this case, you will lose your keys entry1 and so on.

NodeJs console.table in a forloop

so there is this NodeJS module called console.table where you can basically add tables inside the console. Here is an example from their website:
// call once somewhere in the beginning of the app
require('console.table');
console.table([
{
name: 'foo',
age: 10
}, {
name: 'bar',
age: 20
}
]);
// prints
name age
---- ---
foo 10
bar 20
This is a mere example, I tried to automate it by putting it in a forloop, the forloop and code that I had hoped would work is this:
var values = [
]
for(var l = 0;l<config.accounts.username.length;l++) {
values.push([
{
username: "Number "+l,
itemtype: "Hello",
amount: 10
}, {
itemtype: "Hello",
amount: 10
}
]);
}
console.table("", values);
Unfortunatly though, it does not work, can someone help me with this?
Thanks!
You're pushing an array of values into your array - remove the [ & ]
for(var l = 0;l<config.accounts.username.length;l++) {
values.push(
{
username: "Number "+l,
itemtype: "Hello",
amount: 10
}, {
itemtype: "Hello",
amount: 10
}
);
}
Ref: Array.prototype.push
And then your original example didnt take 2 parameters it only took one so this
console.table("", values);
should possibly be
console.table(values);

Replace value of an element in an array of objects

I have an array of objects. If I do a console.log, I see this data.
[Object,Object,Object]
0: Object
Name: Ria
Age: 27
Job: Analytics & Review
1: Object
Name: Brian
Age: 23
Job: Admin
2: Object
Name: Rick
Age: 32
Job: Analytics & Review
As you can see at the Job part, I have & symbol. I want to replace that & with & since html does not allow & to pass directly through ajax since its a reserved entity.
Can someone let me know how I can replace & with & wherever they exist.
You can replace it
var data = [{ Name: 'Ria', Age: 27, Job: 'Analytics & Review'},
{ Name: 'Brian', Age: 23, Job: 'Admin'},
{ Name: 'Rick', Age: 32, Job: 'Analytics & Review'}];
data.forEach(function(currentValue, index, array) {
array[index] = JSON.parse(JSON.stringify(array[index]).replace('&', '&amp'));
});
Idea is to convert your entire array of object into string and then use regex to replace the symbol and then parse back the array of objects back from the string. Try this.
var newArray = JSON.parse(JSON.stringify(array).replace(/&/g,'&amp'));

Categories