Auto-summarising JSON objects [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I want to summarise JSON data objects in a webpage. The only method I can think of is to read it into R, run summarise(), extract the report to json and read that into a webpage and write to DOM. Does anyone know a less idiotic method for getting an equivalent intelligent summary that doesn't involve R?

Is there anything equivalent in Javascript/JQuery for JSON objects?
The closest thing is probably Object.keys and Array#reduce, which visits each array entry (each property name — key — in this case) and calls the callback passing the accumulator for the reduce operation and the value of the entry. So for instance, a sum looks like this:
var obj = {
foo: 42,
bar: 27,
baz: 51
};
var sum = Object.keys(obj).reduce(function(acc, key) {
return acc + obj[key];
}, 0); // <== 0 = seed value for the accumulator
snippet.log(sum);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
Other than that, you're into libraries.

Related

JSON structure in javascript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 days ago.
Improve this question
I am trying to create a javascript structure that looks like that:
[{'red': {color:'red},...}]
starting with an array of colors:
const COLORS = ['red','yellow']
This is what I have tried:
const finalArray = COLORS.map(color => ({ [color]: { color } }))
However this produces an array that looks like that:
[{red: {color:'red'}}]
instead of [{'red': {color:'red'}}]
Which is not the same and will prevent the library I am using from understanding the array.
Any idea is welcome.
I edited the question since there where some typos. Hope it’s clearer now.
Thanks
What are the differences between:
[{red: {color:'red'}}]
// and
[{'red': {color:'red'}}]
If it's only a quote related matters, you can do like:
COLORS.map(color => ({ [`'${color}'`]: { color } }));
These are just two ways of representing the same array/object. If you need a string containing the canonical representation of the array/object (with double quotes around the names of the properties), you can use JSON.stringify(finalArray).
Please note this will quote ALL your property names, like in:
[{"red":{"color":"red"}}]
And please note the above is a string, as if you did:
finalString = '[{"red":{"color":"red"}}]'
(Note: this question has been closed, and I agree it's not clear enough. But it's quite evident that the user is confusing the internal structure of an array/object with its external representation, and with the way the array/object is shown by a development environment, browser, etc. As this is a very common problem, mostly in new programmers or newcomers to a tool, the question and the answers may still be helpful.)

Unusual array with key value NaN property, containing more arrays? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have an unusual Javascript array with a length of 0, but if I expand the array I can see it contains multiple nested arrays with the same property, and eventually an Array containing an object. I've never seen this type of array / object before.
This is a sudo code version (as far I can read it):
[NaN: [{foo:'barr'}]]
But constructing an object like that would cause an error. Can anyone explain what it is?
This is a screen shot of what it looks like console logged in Chrome:
And console logged in Firefox:
It looks like, you have 'NaN' as key, which is possible (arrays are objects), because you may have calculated the index, which goes wrong.
var array = [];
array['x' * 3] = 'value'; // index/key is NaN
console.log(array);
console.log(array.NaN);

Need help extracting string from a text file via regex [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
I'm trying to extract a certain js object from a text/js file via regex.
The whole file contains a lot of code, but I'm only interested in getting a variable called cfg.
The file could look like this:
function A(){
}
var cfg = {
setting:1,
setting2: 5,
setting3:[],
setting4:{
setting5:"test"
}
};
function B(){
}
Could anyone help me to figure out the regex for this ? I'm terrible at regex and I've tried plenty of available solutions but some of them don't seem to be valid in C#.
Right now my solution is using:
string[] split = input.Split(new string[] { "var cfg = " }, StringSplitOptions.None);
if(split.Length > 2)
{
string[] split2 = split[1].Split(new string[] { ";" }, StringSplitOptions.None);
return JObject.Parse(split2[0]);
}
Which obviously doesn't cover different writings of the cfg object. Like var cfg={};
Thanks in advance!
I would recoment you use a JS parser such as Jint if your code is more complex or will change. But for your example this should work:
var r = new Regex(#"var cfg = (?<Content>\{[^;]*});");
var content = r.Match(text).Groups["Content"];
Note: If the cfg literal contains ; the regex will not work as expected.

How to find the value of exponent in Javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
Is there a Math API in javascript to find the value of n (exponent), eg,
Find the value n such that 2**n=64.
i know there is Math.pow , but it requires base and exponent. In my case i have base and the result, so i dont think it would work.
I think you mean to find log of the value
let a = Math.pow(2, 5);
function getBaseLog(x, y) {
return Math.log(y) / Math.log(x);
}
console.log(a, getBaseLog(2, a));
Try this. Refer to this link .
Math.log2(x) // x=64
The link will also tell you about other related Math functions.
Also remember that for finding log of x to the base y, you can always use the formula ln(x)/ln(y) and for ln you already have an inbuilt function (Refer link above).

Typed immutable objects in javascript [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
I am trying organize data types in React Flux-like application. All my data objects are immutable, for collections I am using immutable.js, which is perfect library for that. But for typed objects i use my own classes. I don't think it is the best solution, but i need to somehow handle default values, internal consistency, validations of data, add methods to that objects etc.
Is there some library available for that purpose?
Do you use immutable.js collections also for that kind of objects? So you handle consistency of data, validations and other functionality somewhere else?
Or do you use plain classes for that?
Do you think that is good idea to have typed objects in React/Flux based application?
Here is example of what kind of objects i mean and simple example how I use it.
class Event extends MyImmutableLib {
constructor(plain) {
this.start = plain.start;
this.end = plain.end;
this.name = plain.name || "unnamed event"; // some default value
this.attendants = plain.attendants || [];
this.valid = plain.start < plain.end; // simple check of validity, I can also throw exception if it is needed
Object.freeze(this); // I use freeze to be sure I don't accidentally change the object
}
getDuration() {
return this.end - plain.start; // methods are sometimes useful
}
addAttendant(newPerson) {
return this.set("attendants", this.attendants.concat([newPerson])) //immutable edit, so I return new object
}
}
var someEvent = new Event({start: new Date("2015-02-29"), end: new Date("2012-02-30")}) //
var jsMeetup = someEvent.set("name", "9th Js Meetup, Brno")
var jsMeetup = jsMeetup.addAttendant("Joe");
console.log(jsMeetup.name, jsMeetup.getDuration())
The best would be some library with:
Typed objects - so I would have my data better organized.
Default values
Validations
Methods
Immutability specific functions

Categories

Resources