How to extract values from JSON - javascript

I get a JSON strings through JSONP call. I just know that how the general structure of JSON is going to be but I do not know what will be the values and keys. The general structure will be like this
[
{"key_name": "value"},
{"key_name": "value"},
{"key_name": "value"}
]
I do not know what will be inside curly brackes. How can I reach these values and change them to something like this
[
{name: "key_name", y: value},
{name: "key_name", y: value},
{name: "key_name", y: value}
]
where value is a number
example fiddle:

Use Array.prototype.map() on the array of objects. Fetch the array of keys of an object using Object.keys()
var x = [{
"key_name1": "25"
}, {
"key_name2": "452"
}, {
"key_name3": "32"
}];
var new_x = x.map(function(el) {
return {
"name": Object.keys(el)[0],
"y": +el[Object.keys(el)[0]]
};
});
console.log(new_x);

Related

Filter and loop thru non-array flat JSON object in javascript [duplicate]

This question already has answers here:
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 2 years ago.
I have the following JSON, which I use as some kind of enum equivalent for javascript:
const blah = {
IV: {
name: "dIV",
value: 1
},
III: {
name: "dIII",
value: 2
},
II: {
name: "dII",
value: 3
},
I: {
name: "dI",
value: 4
}
};
I would like to filter all the objects by value and then be able to loop through the result.
I tried to do something like:
let result = blah.find(x => x.value > 2);
result.each(function () {
console.log(this)
}
but this doesn't work and throws: blah.find is not a function.
The expected output would contain two elements:
II: { name: "dII", value: 3},
I: { name: "dI", value: 4}
Most of the examples I've found on the Internet use arrays in the JSON structure. Is there any option
to achieve what I want or I need to modify the JSON structure and use an array?
Cheers
You can iterate over your object (note, it is a javascript literal object, not a JSON) with a simple for...in that loops through each object key (enumerable properties), for me, this is the most controllable and readable way, but there is many more, as you would see in other people answers.
const blah = {IV: {name: "dIV", value: 1}, III: {name: "dIII", value: 2}, II: { name: "dII", value: 3}, I: {name: "dI", value: 4}};
let result = []
for (let key in blah){
let object = blah[key]
if (object.value > 2){
result.push(object)
}
}
console.log(result)
Another possibilty is using Object.values (that returns all values from an object into an array)
and an Array.filter (that the name says all), this is less code and more "elegant":
const blah = {IV: {name: "dIV", value: 1}, III: {name: "dIII", value: 2}, II: { name: "dII", value: 3}, I: {name: "dI", value: 4}};
let result = Object.values(blah).filter(x => x.value > 2)
console.log(result)
I would use Object.entries and reduce.
const blah = {
IV: {
name: "dIV",
value: 1
},
III: {
name: "dIII",
value: 2
},
II: {
name: "dII",
value: 3
},
I: {
name: "dI",
value: 4
}
};
var result = Object.entries(blah).reduce((obj, [key, props]) => {
if (props.value >= 3) {
obj[key] = props
}
return obj
}, {})
console.log(result)
try Object.keys(blah):
const blah = {
IV: {
name: "dIV",
value: 1
},
III: {
name: "dIII",
value: 2
},
II: {
name: "dII",
value: 3
},
I: {
name: "dI",
value: 4
}
};
var result = Object.keys(blah)
.filter(key => blah[key].value > 2)
.reduce((acc, key) => ({...acc, [key]: blah[key]}), {});
console.log(result)
What you have provided in the example is not in fact JSON (Javascript Object Notion), but an actually Javascript object, the birthplace of the JSON serialisation format.
JavaScript objects are more like dictionaries, and provide fast key/value read/writes for structured data. You cannot sort a Javascript object because it is unordered, depending on the javascript engine's implementation (V8 for Chrome, Node.js, ...).
What you can do, is get a list of keys/values/key+values as an array, and iterate over the array, either using the array's values to construct a new object, or just as a reference for a list of keys that exist in the object.
See Object.keys, Object.values and Object.entries on Mozilla MDN. Arrays are ordered, can be sorted and iterated over.

How can I set a jsonarray inside the jsonobject?

How can I set a jsonarray inside the jsonobject?
I want to be able to push the values ​​but I do not know exactly what to do
sample :
{
"ContactsDetails": [
{
"Prefix": "string",
"FirstName": "string",
"LastName": "string",
"Mobile": "string",
"EmojiId": "byte"
}
],
"GroupId": integer
}
Here is the sample code what you're looking for.
let empty = {}; // init a empty object.
empty["ContactsDetails"] = []; // array creation
empty["GroupId"] = 45; // number adding
// creating a new object
let c_details = {
"Prefix": "string",
"FirstName": "string",
"LastName": "string",
"Mobile": "string",
"EmojiId": "byte"
};
// adding an existing obj to array, push operation
empty["ContactsDetails"].push(c_details);
// print object
console.log(empty);
// this will convert the object to JSON.
console.log(JSON.stringify(empty))
What you call a JSONArray is simply a Javascript array like []. You can set it like any property of an Object (JSON).
In Javascript, an Object (symbolized as {}) will be represented as a JSON Object and a Array (symbolized by []) will be represented as a JSON Array.
So you can just do something like this :
var object = {};
object.foo = [];
object.foo.push("newvalue");
object.foo.push("bar");
console.log(object);
And of course, you can push an Object in your array like this :
var array = [];
array.push({ foo: "bar" });
console.log(array);
Arrays and objects are structures that can recursively contain themselves, or each other. JSON is just a format that represents these recursive data structures.
Luckily, you can define all of these in JavaScript using plain literals:
An array literal is wrapped within brackets []
An object literal is wrapped within curly brackets {}
Hence, you can build an array of objects:
[
{name: 'x', data: 0},
{name: 'y', data: 1}
]
Or an object that its parameters are arrays:
{
array0: [0, 1],
array1: [2, 3]
}
And, as I mentioned above, you can also use these structures recursively. For example:
[
{id: 0, array: [0, 1]},
{id: 1, array: [2, 3]}
]

Elegant way to select key in object of an array

Consider having the following json
[
{'key1': { ... }},
{'key2': { ... }},
{'key3': { ... }}
]
I want to extract the keys for those objects in an elegant way, the following code is working, but it seems ugly to me.
let result = objects.map(o => Object.keys(o))[0]
the [0] at the end because the returned value is an array of array
You can use .concat() and .map() methods to get the desired result:
let data = [
{'key1': { }},
{'key2': { }},
{'key3': { }}
];
let result = [].concat(...data.map(Object.keys));
console.log(result);
References:
Array.prototype.concat()
Array.prototype.map()
Object.keys()
Spread Syntax
An array can only hold values, objects hold key/value pairs. Don't forget to use JSON.parse(json) before actually manipulating the data.
I'm guessing you need something along the lines of:
const list = [
{1: "one"},
{2: "two"},
{3: "three"}
];
I edited your JSON.
const data = [
{ 'key2': { }} ,
{'key1': { }},
{'key3': { }}
];
const result = [].concat.apply([], data.map(Object.keys));
console.log(result);

Arrange objects by property with specific order using javascript

Is there a way that I could arrange an array of objects according to a certain property whose order is based on an external array (not just alphabetically, numerically, etc.)?
For example, let's say I have a temporary array:
var tempArray = ["b", "a", "d", "c"];
and an array of objects:
var objectArray = [
{ name: "John",
section: "a" },
{ name: "Joe",
section: "b" },
{ name: "Mike",
section: "c" },
{ name: "Mark",
section: "d"}
];
Can I rearrange objectArray so that the object order would follow the contents of tempArray hence returning objectArray as:
objectArray = [
{ name: "Joe",
section: "b" },
{ name: "John",
section: "a" },
{ name: "Mark",
section: "d" },
{ name: "Mike",
section: "c"}
]; // desired output
Any help is very much appreciated.
something like this:
var sorted = objectArray.sort(function(a, b){
return tempArray.indexOf(a.section)-tempArray.indexOf(b.section)
});
You can do that with Array#sort and Array#indexOf. Array#sort sorts arrays, and you can give it a function to call that accepts two arguments, which are two entries to compare to determine which should be before the other. Array#indexOf tells you the index of an entry in the array. So if you use Array#sort on objectArray, and within your callback use Array#indexOf on tempArray to look up the indexes of each object's section property, then compare the indexes (or probably just subtract the second object's index from the first).

How to append this JavaScript array object to another JavaScript array object?

I have this Javascript json array object;
var dataJson=[ [{v:1},{v:90}],[{"v":2},{"v":"33.7000"}] ];
I want to append this array object dataJson to another object such that it looks like this;
var chartObject = {"cols": [
{id: "t", label: "t_label", type: "number"},
{id: "s", label: "s_label", type: "number"}
], "rows": [
{c:
[{v:1},{v:90}] //dataJson[0]
},
{c:
[{"v":2},{"v":"33.7000"}] ////dataJson[1]
}
]};
How do I use a for loop to insert dataJson elements into chartObject? I am sorry I am quite new to javascript and can't even produce some starting code. Thank you very much for any help.
Try this:
...
], "rows": dataJson.map(function(row) {return {c:row};})
};
Javascript objects are pretty amazing things. Just define a new field in chartObject as an array, and then push whatever json data you want into it. It looks you want rows to be an array of objects which have an identifier for each json object, but unless you explicitly want to name each dataJson with a string, then just use an indexed array:
chartObject["rows"] = [];
for(var i = 0; i < dataJson.length; i++) {
chartObject["rows"].push(dataJson[0]);
}
Now you can access each piece of data with:
chartObject["rows"][index]
And each field in the data with:
chartObject["rows"][index]["v"]
Using the simple and clean way:
var chartObject = {"cols": [
{id: "t", label: "t_label", type: "number"},
{id: "s", label: "s_label", type: "number"}
]};
var dataJson=[ [{v:1},{v:90}],[{"v":2},{"v":"33.7000"}] ];
chartObject["rows"] = []; // start with empty array
// iterate over first dataJson array
for(var i = 0, len = dataJson[0].length; i < len; i++){
// push in array `c` mapped to the i-th element of dataJson[0]
chartObject["rows"].push({c : dataJson[0][i]["v"]});
}
console.log(chartObject);
DEMO
Ignore those [object Object] in DEMO
Sample Output:
{
cols: [{
id: "t",
label: "t_label",
type: "number"
}, {
id: "s",
label: "s_label",
type: "number"
}],
rows: [{
c: 1
}, {
c: 90
}]
}

Categories

Resources