I have a generic JSON structure I want to put in to a JavaScript object.
My JSON is like this
{
"rows": [
{
"items": [
{
"key": "foo1",
"value": "bar1"
} ,
{
"key": "foo2",
"value": "bar2"
}
]
}
] }
What is the easiest way to convert this in to a JS object like this:
Item.foo1 = 'bar1';
Item.foo2 = 'bar2';
I can use something like JSONPath
But I thought maybe there is a simpler way to do this? using straight JavaScript?
Live at http://www.jsfiddle.net/QcLk8/2/
var json = {
"rows": [
{
"items": [
{
"key": "foo1",
"value": "bar1"
} ,
{
"key": "foo2",
"value": "bar2"
}
]
}
] }
var items={}
var jsonItems = json.rows[0].items;
for(var idx=0;idx<jsonItems.length;idx++)
{
var item = jsonItems[idx];
items[item.key] = item.value;
}
alert(items.foo1);
Something like
var Item = {};
var items = object.rows.items;
for (var i=0; i<items.length; i++) {
Item[items[i].key] = items[i].value;
}
?
Related
I have an array of data that looks like this:
{
"data": [
{
"id": "20200722_3",
"eventDate": "2020-07-22T00:00:00",
"eventName": "Football",
"eventDetails": [
"Men's First Round (2 matches)"
],
"eventVenue": "Venue A"
},
{
"id": "20200722_1",
"eventDate": "2020-07-22T00:00:00",
"eventName": "Football",
"eventDetails": [
"Men's First Round (2 matches)"
],
"eventVenue": "Venue B"
}
]
}
Now I wanted to group the data by multiple properties. For example, by eventDate, eventName, eventDetails, and eventVenue. Which I've done with this code referenced from this post:
const groupBy = (array, attrs) => {
var output = [];
for (var i = 0; i < array.length; ++i) {
var ele = array[i];
var groups = output;
for (var j = 0; j < attrs.length; ++j) {
var attr = attrs[j];
var value = ele[attr];
var gs = groups.filter(g => {
return g.hasOwnProperty('label') && g['label'] === value;
});
if (gs.length === 0) {
var g = {};
if (isArray.g['label'] ) {
}
g['label'] = value;
g['groups'] = [];
groups.push(g);
groups = g['groups'];
} else {
groups = gs[0]['groups'];
}
}
groups.push(ele);
}
return output;
}
var result = groupBy(data, ['eventDate', 'eventName', 'eventDetails', 'eventVenue'])
Which results in an array like this:
[{
"label": "2020-07-23T00:00:00",
"groups": [{
"label": "Football",
"groups": [{
"label": [
"Men's First Round (2 matches)"
],
"groups": [{
"label": "Venue A",
"groups": [
"Object"
]
}]
},
{
"label": [
"Men's First Round (2 matches)"
],
"groups": [{
"label": "Venue B",
"groups": [
"Object"
]
}]
}
}]
}]
}]
You can see that for the output above, there are two separate "groups" that have the label "Men's First Round (2 matches)". I'm trying to figure out how I can combine these objects that have duplicate value ? I'm looking for something that would output like this:
[{
"label": "2020-07-23T00:00:00",
"groups": [{
"label": "Football",
"groups": [{
"label": [
"Men's First Round (2 matches)"
],
"groups": [{
"label": "Venue A",
"groups": [
"Object"
]
},
{
"label": "Venue B",
"groups": [
"Object"
]
}]
}]
}]
}]
Any help would be greatly appreciated.
I'll share the answer that I came up with for those that are curious.
For my needs, I know that if the array with the eventName only contained 1 attribute, it could be a duplicate. So in order to fix that, I converted the array that only had 1 value to a string:
if (ele[attr] && ele[attr].length === 1) {
var value = ele[attr].toString();
} else {
var value = ele[attr];
}
I would be very grateful if someone suggested how to get such a JSON
[
{
"type": "A_TYPE",
"value": "foo"
},
{
"type": "A_TYPE",
"value": "bar"
},
{
"type": "B_TYPE",
"value": "qux"
},
{
"type": "C_TYPE",
"value": [
10000,
19999
],
"name": "1xxxx"
}
]
from such a JSON
[
{
"type": "A_TYPE",
"value": [
"foo",
"bar"
]
},
{
"type": "B_TYPE",
"value": [
"qux"
]
},
{
"type": "C_TYPE",
"value": [
[
10000,
19999
]
]
}
]
In this case, objects with a property like "type":"A_TYPE" in which you want to combine "value":"" can be more than one.
Thank you in advance for your help!
I made this solution to your question.
let arr = [
{
"type": "A_TYPE",
"value": [
"foo",
"bar"
]
},
{
"type": "B_TYPE",
"value": [
"qux"
]
},
{
"type": "C_TYPE",
"value": [
[
10000,
19999
]
]
}
];
let newArr = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].value.length; j++) {
let value = arr[i].value[j]; // Get value from the object
let type = arr[i].type; // Get type from the object
// New Object to push to the new Array
let tempObj = {};
tempObj.type = type;
tempObj.value = value;
newArr.push(tempObj); // Push object to array
}
}
console.log(JSON.stringify(newArr));
Test it here
I'm trying to change the structure of a json by removing duplicate keys. Otherwise, to put the children of a same name inside only one name node.
Current JSON:
{
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{
"name": "AgglomerativeCluster",
"size": [
"3938"
]
}
]
}
]
},
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{
"name": "CommunityStructure",
"size": [
"3812"
]
}
]
}
]
}
]
}
Desired output:
{
"name": "flare",
"children": [
{
"name": "analytics",
"children": [
{
"name": "cluster",
"children": [
{
"name": "AgglomerativeCluster",
"size": 3938
},
{
"name": "CommunityStructure",
"size": 3812
}
]
}
]
}
]
};
Thanks for your help.
Typically, StackOverflow isn't the place to have people write code for you, and your question should be more specific as to with what part of your algorithm you are having trouble. However, this looked fun, so I did it.
I solved this by first converting it to an object whose properties are the names and values are the children/size. This insured that each named instance was grouped with other named instances.
var mutate = function(desired, current) {
for (var x = 0; x < current.length; x++) {
if (Object.hasOwnProperty.call(current[x], 'size')) {
desired[current[x].name] = parseInt(current[x].size[0], 10);
}
else {
if (!Object.hasOwnProperty.call(desired, current[x].name)) {
desired[current[x].name] = Object.create(null);
}
mutate(desired[current[x].name], current[x].children);
}
}
return desired;
};
I then converted that back to your original desired format by iterating over the Object.entries (key/value pairs).
var mutate2 = function(current) {
var desired = [];
var entries = Object.entries(current);
for (var x = 0; x < entries.length; x++) {
var o = Object.create(null);
o.name = entries[x][0];
if (typeof entries[x][1] === 'number') {
o.size = entries[x][1];
}
else {
o.children = mutate2(entries[x][1]);
}
desired.push(o);
}
return desired;
};
You get your result by using this hideous beast:
var desiredJson = mutate2(mutate(Object.create(null), [ currentJson ]));
console.log(desiredJson);
I have this array that needs to be parsed into a useful object. The names of each value are a collection of namespaces separated by / characters. The values between each '/' need to be turned into a JS Objects property:
"status": [
{
"message": "OK",
"name": "/Computer",
"values": []
},
{
"name": "/Computer/CPU Usage",
"values": []
},
{
"name": "/Computer/CPU Temp",
"values": []
},
{
"name": "/Computer/hardware/memory",
"values": []
}
]
I need it to become this:
"status": {
"computer": {
"CPU Usage": {
"values": []
},
"CPU Temp": {
"values": []
},
"hardware": {
"memory": {
"values": []
}
}
}
}
So far I have done this:
var statii = status, // from above..
_parsedStatii = {};
for (var i = 0; statii.length < 0; i ++) {
var _nameSpaces = statii[i].name.split('/');
// Start at 1 because index 0 is empty (before the first slash)
if (!_parsedStatii[_nameSpaces[1]]) {
_parsedStatii[_nameSpaces[1]] = {};
}
if (!_parsedStatii[_nameSpaces[1]][_nameSpaces[2]])
_parsedStatii[_nameSpaces[1]][_nameSpaces[2]] = {};
if (!_parsedStatii[_nameSpaces[1]][_nameSpaces[2]][_nameSpaces[3]])
_parsedStatii[_nameSpaces[1]][_nameSpaces[2]][_nameSpaces[3]] = {};
if (!_parsedStatii[_nameSpaces[1]][_nameSpaces[2]][_nameSpaces[3]][_nameSpaces[4]])
_parsedStatii[_nameSpaces[1]][_nameSpaces[2]][_nameSpaces[3]][_nameSpaces[4]] = {};
}
Obviously it is no where near right, I have tried a lot of recursive functions but am at a bit of a loss. This example gives the clearest representation of what I am trying to achieve. Any ideas? (Please excuse code typos, it was paraphrased)
You could split the name and build an object upon.
var data = { "status": [{ "message": "OK", "name": "/Computer", "values": [] }, { "name": "/Computer/CPU Usage", "values": [] }, { "name": "/Computer/CPU Temp", "values": [] }, { "name": "/Computer/hardware/memory", "values": [] }] },
object = {};
data.status.forEach(function (a) {
a.name.slice(1).split('/').reduce(function (o, k) {
return o[k] = o[k] || {};
}, object).values = a.values;
});
console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have an object that looks like this:
{
"KeyValueOfstringstring": [
{
"Key": "FET",
"Value": "123"
},
{
"Key": "FFS2",
"Value": "Z"
},
{
"Key": "LoadIndex",
"Value": "91"
},
{
"Key": "Ply",
"Value": "B"
}
]
}
and i want it to look like this:
{
"KeyValueOfstringstring": [
{
"FET": 123,
"FFS2": "Z",
"LoadIndex": "91",
"Ply": "B"
}
]
}
Has anyone done this before or has any idea how this could be accomplished? Unfortunately this is the response from a WS and thus have to work with it.
You can do it with a regular for loop:
var result = {};
for (var i = 0; i < object.array_with_long_name.length; i++) {
var o = object.array_with_long_name[i];
result[o.Key] = o.Value;
}