Insert jsonobject into new array - javascript

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))

Related

Object.assign() for replacing objects of a json

I have JSON looks like this:
{
"ArrayInfo": [
{
"name": "A",
"Id": "1"
},
{
"name": "B",
"Id": "2"
},
{
"name": "C",
"Id": "3"
},
{
"name": "D",
"Id": "4"
}
]
}
I want to replace an object of JSON with another object.For example I have this object :
{"name":"E","Id":"5"}
and it is going to be replaced by this object of JSON:
{"name":"B","Id":"2"}
JSON should look like this :
{
"ArrayInfo": [
{
"name": "A",
"Id": "1"
},
{
"name": "E",
"Id": "5"
},
{
"name": "C",
"Id": "3"
},
{
"name": "D",
"Id": "4"
}
]
}
What I did is to use Object.assign but the new object will be added to array instead of replacing.
(all the data is going to be dynamic but for making more understandable I use static data)
const itemToReplace = { "name": "E", "Id": "5" };
const prevItem = ArrayInfo[2]
ArrayInfo = ArrayInfo.map((el, idx) => {
return Object.assign({}, el, { prevItem: itemToReplace });
});
let NewArryInfo = ArrayInfo
console.log(NewArryInfo)
The result of console.log(NewArryInfo) :
{
"ArrayInfo": [
{
"name": "A",
"Id": "1"
},
{
"name": "B",
"Id": "2"
},
{
"name": "C",
"Id": "3"
},
{
"name": "D",
"Id": "4"
}
{
"name": "E",
"Id": "5"
}
]
}
You can use Array.prototype.splice to replace an item in Array.
const replaceItem = {"name":"E","Id":"5"}
const ArrayInfo = [
{
"name": "A",
"Id": "1"
},
{
"name": "B",
"Id": "2"
},
{
"name": "C",
"Id": "3"
},
{
"name": "D",
"Id": "4"
}
];
ArrayInfo.splice(1, 1, replaceItem); // remove second item and replace
console.log(ArrayInfo);
const object = {
"ArrayInfo": [{
"name": "A",
"Id": "1"
},
{
"name": "B",
"Id": "2"
},
{
"name": "C",
"Id": "3"
},
{
"name": "D",
"Id": "4"
}
]
};
const objectToReplace = {
"name": "B",
"Id": "2"
};
const updatedObject = Object.assign({}, object, {
ArrayInfo: object.ArrayInfo.map((info) => {
if (info.Id === objectToReplace.Id && info.name === objectToReplace.name) {
return {
"name": "E",
"Id": "5"
};
}
return info;
})
});
console.log(updatedObject);
const myArr = [
{
"name": "A",
"Id": "1"
},
{
"name": "B",
"Id": "2"
},
{
"name": "C",
"Id": "3"
},
{
"name": "D",
"Id": "4"
}
];
const replaceObj = (arr, objReplaced, objToReplaceWith) => {
const replacedObjIndex = arr.findIndex(item => JSON.stringify(item) === JSON.stringify(objReplaced));
arr[replacedObjIndex] = objToReplaceWith;
console.log(arr)
return arr;
}
replaceObj(myArr, {"name":"B","Id":"2"}, {"name":"E","Id":"5"});
In this way you can replace any object, from any position in the array.
You won't have to worry about the position of the item that you want to replace in the array and also you won't need to worry about it's keys or values.
When you map over the array you could check if each item is the one you want to replace, and if it is, return the new item instead.
ArrayInfo = ArrayInfo.map((el, idx) => {
if (el.id === prevItem.id && el.name === prevItem.name) {
return itemToReplace;
}
return el;
});
Try this!
let ArrayInfo = [{"name": "A","Id": "1"},{"name": "B","Id": "2"},{"name": "C","Id": "3"},{"name": "D","Id": "4"}];
const onReplace = {"name":"E","Id":"5"};
const toReplace = {"name": "B","Id": "2"};
function replaceArray(array, onReplace, toReplace) {
const removeIndex = array.map(item => { return item.name; }).indexOf(toReplace.name);
array.splice(removeIndex, removeIndex, onReplace);
return array
}
console.log(replaceArray(ArrayInfo, onReplace, toReplace));

Object assign overrides previous object when values are the same

So I am expecting this object when using Object.assign on object1 and object2. There is unknown number of objects 1 - n range.
var expectedObject = [{
"question": {
"value": "foo"
},
"question2": {
"value": "foo1"
},
"question3": {
"value": ["fooArray"]
}
},
{
"question": {
"value": "foo1"
},
"question2": {
"value": "foo2"
},
"question3": {
"value": ["foo1Array"]
}
}];
var object1 = {
"question": {
"value": "foo"
},
"question2": {
"value": "foo1"
},
"question3": {
"value": ["fooArray"]
}
};
var object2 = {
"question": {
"value": "fooIOverrideYouSucker"
},
"question2": {
"value": "fooIOverrideYouSucker1"
},
"question3": {
"value": ["fooIOverrideYouSuckerWonArray"]
}
}
var allItems = {};
// This will be running inside loop - object1 and object2 are just an examples to simplify the case
Object.assign(allItems, object1, object2);
console.log(JSON.stringify([allItems]));
The results I am getting:
[{
"question": {
"value": "fooIOverrideYouSucker"
},
"question2": {
"value": "fooIOverrideYouSucker1"
},
"question3": {
"value": ["fooIOverrideYouSuckerWonArray"]
}
}]
Is there a nice way to simply append multiple same objects into existing object?
Thank you.
Fiddle with above example.
https://jsfiddle.net/bielus86/fad4w2Lo/10/
If you are looking to create an array with the two objects, you can simply do [object1, object2] or
var allItems = [];
allItems.push(object1);
allItems.push(object2);

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]}
)}

Transform/parse javascript object key value pairs

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

Deleting a row from javascript object

I have a javascript object which looks like this :-
var myObject = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"},
{"id": "2", "URL": "http://shsusadhf.com", "value": "2"},
{"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];
Now , I have to delete all the rows in the object with id value 2. How can this be done ?
If you don't need the original array after "deleting" rows, you can use splice like this:
http://jsfiddle.net/rmcu5/1/
var myArray = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"},
{"id": "2", "URL": "http://shsusadhf.com", "value": "2"},
{"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];
function removeItemsById(arr, id) {
var i = arr.length;
if (i) { // (not 0)
while (--i) {
var cur = arr[i];
if (cur.id == id) {
arr.splice(i, 1);
}
}
}
}
removeItemsById(myArray, "2");
console.log(JSON.stringify(myArray));
It doesn't create a new array, just modifies the original in place. If you need the original array and all of its items, then use one of the other solutions that return you a modified copy of the original.
Note that what you call myObject is actually an array therefore you can use array methods on it:
myObject = myObject.filter(function( obj ) {
return obj.id != 2;
});
Demo: http://jsfiddle.net/elclanrs/LXpYj/
try this:
function deleteObject(array,id)
{
var newObject=[];
for (var o in array) {
if(array[o].id!=id)
newObject.push(array[o]);
}
return newObject;
}
working JS fiddle
You can do without creating new array, you need to write remove function:
Array.prototype.remove = function() {
var what, a = arguments, L = a.length, ax;
while (L && this.length) {
what = a[--L];
while ((ax = this.indexOf(what)) !== -1) {
this.splice(ax, 1);
}
}
return this;
};
Without New Array Delete Object
try it with filter (its an array not a object)
var rr = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"}, {"id": "2", "URL": "http://shsusadhf.com", "value": "2"}, {"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];
rr = rr.filter(function(e) {
return e.id != 2;
});
Here you go, this is without recreating the array or anything.
var myObject = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"},
{"id": "2", "URL": "http://shsusadhf.com", "value": "2"},
{"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];
for(i=0,iMax=myObject.length;i<iMax;i++){
(function (a) {
if(this.id=="2"){
delete myObject[a];
}
}).call(myObject[i],i);
}
console.log(myObject);
​
​
jsFiddle
http://jsfiddle.net/gG2zz/1/

Categories