Transform/parse javascript object key value pairs - javascript

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;
}

Related

How can I combine/serialize such JSON objects by means of Node.js or NPM modules?

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

How to implement single indexed array using javascript linkedlist

I have an array like This
var arrays = [
{
"value": "$6"
},
{
"value": "$12"
},
{
"value": "$25"
},
{
"value": "$25"
},
{
"value": "$18"
},
{
"value": "$22"
},
{
"value": "$10"
}
];
I need to implement these array to single indexed array like following array.
[{
"value": "$6",
"Next": {
"value": "$12",
"Next": {
"value": "$25",
"Next": {
"value": "$25",
"Next": {
"value": "$28",
"Next": {
"value": "$22",
"Next": {
"value": "$10"
}
}
}
}
}
}
}]
How can i implement second array push to first array like above array using javascript linkedlist.
Convert the array into a linked list using Array#reduce method, wherein each iteration construct the object/node and pass the next reference for next iteration. As we need to traverse the linked list, we need to keep a reference of root/head object.
var arrays = [{
"value": "$6"
},
{
"value": "$12"
},
{
"value": "$25"
},
{
"value": "$25"
},
{
"value": "$18"
},
{
"value": "$22"
},
{
"value": "$10"
}
];
var root = {};
arrays.reduce((acc, { value }) => {
acc.next = { value };
return acc.next;
}, root);
var result = [root.next];
console.log(result);
Hope this will help!
It will iterate the array in reverse direction and maintaining the previous value and appending it into the current one and return the output.
Try this
function parseData(input){
var output = [];
var len = input.length;
var previous = {};
for(var i =len-1 ; i >= 0; i--){
var temp = {};
temp["value"] = input[i].value;
if(i !== len){
temp["Next"] = previous;
}
previous = temp;
}
output.push(previous);
return output;
}
try this
let result=[];
for(let i=0; i<arrays.length; i++){
result.push(
{"value":arrays[i]["value"], "next":arrays[i+1]}
)}

Use array of strings to create a multi level object, parsing arrays into JS objects

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; }

Insert jsonobject into new array

Say that you have the following jsonObject
var arrayWithValuesAndGroups = [{
"TestObject": "Object1",
"GraphGroup": {
"Test": {
"Group": "A",
"Value": "6"
},
"Test2": {
"Group": "B",
"Value": "5"
}
}
},
{
"TestObject": "Object2",
"GraphGroup": {
"Test": {
"Group": "A",
"Value": "9"
},
"Test2": {
"Group": "B",
"Value": "12"
}
}
},
{
"TestObject": "Object3",
"GraphGroup": {
"Test": {
"Group": "A",
"Value": "99"
},
"Test2": {
"Group": "B",
"Value": "16"
}
}
}
]
I want to create a new object with all groups and all values that have that group should be in that array. For example I want the above object to be converted into the bellow
{
"A": {
"Test1": {
"0": "6",
"1": "9",
"2": "99"
}
},
"B": {
"Test2": {
"0": "5",
"1": "12",
"2": "16"
}
}
}
What strategy would you use?
You need to transform one data structure to another.
This is typically done by creation of new object and setting its values from original object within a series of transformations (which in this case are iterations, array creations, value assignments).
While it can be easily done with vanilla js, you can also use lodash library which greatly facilitates such transformations by giving methods to iterate, access keys, values and so on.
I'd not give you an exact solution for your specific data objects just because 1) you've asked about strategy 2) SO is't a place to ask others do your work 3) an answer should be useful to other persons with other data structures.
Try this.
Concept of Object and Array is very important on js and another code.
Practice is only way.
var newObject = {};
for(var i=0,iLen=arrayWithValuesAndGroups.length;i<iLen;i++){
var TestGroupObject = arrayWithValuesAndGroups[i];
console.log(TestGroupObject);
// {
// "TestObject": "Object1",
// "GraphGroup": {
// "Test": {
// "Group": "A",
// "Value": "6"
// },
// "Test2": {
// "Group": "B",
// "Value": "5"
// }
// }
// }
var GraphGroupObject = TestGroupObject.GraphGroup;
console.log(GraphGroupObject);
// {
// "Test": {
// "Group": "A",
// "Value": "6"
// },
// "Test2": {
// "Group": "B",
// "Value": "5"
// }
// }
var GraphGroupObjectKeys=Object.keys(GraphGroupObject);
for(var j=0,jLen=GraphGroupObjectKeys.length;j<jLen;j++){
var GraphGroupObjectKey = GraphGroupObjectKeys[j];
console.log(GraphGroupObjectKey)
// keys are Test, Test2
// GraphGroupObject[GraphGroupObjectKey]
// {
// "Group": "A",
// "Value": "6"
// }
var Group = GraphGroupObject[GraphGroupObjectKey].Group;
var Value = GraphGroupObject[GraphGroupObjectKey].Value;
if(!newObject[Group]){
newObject[Group]={};
}
if(!newObject[Group][GraphGroupObjectKey]){
newObject[Group][GraphGroupObjectKey]={};
}
newObject[Group][GraphGroupObjectKey][i] = Value;
}
}
May be following code can help u to solve this, fiddle http://jsfiddle.net/jesamzjv/
function GetMyFormat(arrayWithValuesAndGroups){
var finalOb = {};
pushToOb = function(group, value, test){
if(!finalOb[group]){
finalOb[group] = {};
finalOb[group][test] = {};
}
var myOb = finalOb[group][test];
var count = Object.keys(myOb).length;
myOb[count] = value;
}
addToAnAr = function(ob){
for (var i in ob){
pushToOb(ob[i].Group,ob[i].Value,i)
}
}
for(var i in arrayWithValuesAndGroups){
item = arrayWithValuesAndGroups[i];
addToAnAr( item["GraphGroup"] );
}
return finalOb;
}
console.log(GetMyFormat(arrayWithValuesAndGroups))

Generic JSON object

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;
}
?

Categories