How to implement single indexed array using javascript linkedlist - javascript

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

Related

Find and replace in nested objects

I'm struggling with the following issue:
I have a nested object. From the server I get a response with an object with changed values. So I want to find the object in my nested object and replace it.
My object has a structure like this:
$scope.page = {
id: 5,
label: 'myPage',
items : [
{
"type": "Container",
"id": 1,
"label": "header",
"items": [
{
"type": "Container",
"id": 2,
"label": "left",
"items": [
{
"type": "Menu",
"label": "settings-menu",
"id": "5"
},
{
"type": "Menu",
"label": "main-menu",
"id": "7"
}
]
},
{
"type": "Container",
"id": 4,
"label": "right",
"items": [
{
"type": "Post",
"label": "contact",
"id": "25"
}
]
}
]
},
{
"type": "Postlist",
"label": "nieuwsberichten",
"id": "17"
},
{
"type": "HTML",
"label": "over deze site",
"id": "18"
},
{
"type": "Other",
"label": "twitter feed",
"id": "19"
}
]
}
From the server I get a new object:
var newItem = {
"type": "Post",
"label": "contact",
"id": "25"
}
How can I update the object inside $scope.page the right way? I've tried the following:
$scope.findAndReplace(newItem,$scope.page.items);
$scope.findAndReplace = function(newItem, items) {
for (var i = 0; i < items.length; i++) {
if (items[i].id == newItem.id) {
items[i] = newItem;
} else if (items[i].items) {
$scope.findAndReplace(newItem, items[i].items);
}
}
}
and:
var oldItem = $scope.findById(item.id, $scope.page.items);
oldItem = newItem;
$scope.findById = function(id, items) {
var match = null;
angular.forEach(items, function(i){
if (match == null) {
if (i.id == id) {
match = i;
} else if (i.items) {
match = $scope.findById(id, i.items)
}
}
})
return match;
}
Neither of these options work. That's because of the nested loops where the object isn't the one in $scope.page anymore.
Anyone an idea to handle this?
Your example looks fine, can't understand why they are not working.
Neither of these options work. That's because of the nested loops where the object isn't the one in $scope.page anymore.
You can keep object reference by using angular.copy(newItem, oldItem)
Hi I have created a fiddle for you.
click for fiddle
for(var indx=0; indx < $scope.page.items.length; indx++) {
var tmpObj = $scope.page.items[indx];
if(tmpObj.hasOwnProperty('items')) {
// check inside
for(var indx1=0; indx1<tmpObj.items.length; indx1++ ) {
var innerObj = tmpObj.items[indx1];
// check for next level
if(innerObj.hasOwnProperty('items')) {
for(var counter=0; counter< innerObj.items.length; counter++) {
var thirdTmp = innerObj.items[counter];
console.log('3rd level inner object', thirdTmp);
if(thirdTmp.id === newItem.id) {
innerObj.items[counter] = newItem;
tmpObj.items[indx1] = innerObj;
$scope.page.items[indx] = tmpObj;
}
}
}
}
} else if(tmpObj.id === newItem.id) {
$scope.page.items[indx] = newItem;
}
};

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

Create JSON structure from JSON result that has many records

Friends, further to my question regarding Creating JSON structure from JSON results how can i create my object that has many headers from the array?
Here is my Fiddle and my code is below.
var array = [
[{
"label": "NewNetworkServiceProvider",
"value": "NewNetworkServiceProvidered46c4ee-7ec1-45d6-9d13-94e301d2f890"
}, {
"label": "PurchaseOrderNumber",
"value": "PurchaseOrderNumber4be9f460-0c98-4038-910d-027565f83e1c"
}, {
"label": "RawRecordType",
"value": "RawRecordType2a774afb-0fd4-4fd4-a3c6-88041de5b1ad"
}],
[{
"label": "NewNetworkServiceProvider",
"value": "NewNetworkServiceProvidered46c4ee-7ec1-45d6-9d13-94e301d2f890"
}, {
"label": "PurchaseOrderNumber",
"value": "PurchaseOrderNumber4be9f460-0c98-4038-910d-027565f83e1c"
}, {
"label": "RawRecordType",
"value": "RawRecordType2a774afb-0fd4-4fd4-a3c6-88041de5m321"
}]
];
var obj = {
header: {}
};
array.forEach(function (item) {
item.forEach(function (data) {
obj.header[data.label] = data.value;
});
});
console.log(obj)
At a guess I think you want this:
array.forEach(function (item) {
item.forEach(function (data) {
obj.header[data.label] = obj.header[data.label] || [];
obj.header[data.label].push(data.value);
});
});
http://jsfiddle.net/867mb14s/1/
Your array is incorrect. the JS code you provided works perfectly if you have different label names, if label names are same then the latest values will replace the old values.
So , try this code. it gives all header names.
var array = [
[{
"label": "0_NewNetworkServiceProvider",
"value": "0_NewNetworkServiceProvidered46c4ee-7ec1-45d6-9d13-94e301d2f890"
}, {
"label": "0_PurchaseOrderNumber",
"value": "0_PurchaseOrderNumber4be9f460-0c98-4038-910d-027565f83e1c"
}, {
"label": "0_RawRecordType",
"value": "0_RawRecordType2a774afb-0fd4-4fd4-a3c6-88041de5b1ad"
}],
[{
"label": "1_NewNetworkServiceProvider",
"value": "1_NewNetworkServiceProvidered46c4ee-7ec1-45d6-9d13-94e301d2f890"
}, {
"label": "1_PurchaseOrderNumber",
"value": "1_PurchaseOrderNumber4be9f460-0c98-4038-910d-027565f83e1c"
}, {
"label": "1_RawRecordType",
"value": "1_RawRecordType2a774afb-0fd4-4fd4-a3c6-88041de5m321"
}]
];
var obj = {
header: {}
};
array.forEach(function(item) {
item.forEach(function(data) {
obj.header[data.label] = data.value;
});
});
console.log(obj)
See the difference in array data.
And #Jaromanda X is also correct, but he is fetching records as array inside each header.

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

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

Categories