Deleting a row from javascript object - javascript

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/

Related

Compare two arrays having objects and remove duplicates from first array

I have two arrays that contain objects. From first array how can I remove the items that are already present in the second array?
First array:
var s = [
{"Name": "1"},
{"Name": "2"},
{"Name": "3"},
{"Name": "4"},
{"Name": "5"},
{"Name": "6"}
]
Second array:
var t = [
{"Name": "1"},
{"Name": "2"},
{"Name": "3"},
{"Name": "8"}
]
Expected output:
[
{"Name": "4"},
{"Name": "5"},
{"Name": "6"}
]
You can use filter() along with some()
var s = [{"Name":"1"},{"Name":"2"},{"Name":"3"},{"Name":"4"},{"Name":"5"},{"Name":"6"}];
var t = [{"Name":"1"},{"Name":"2"},{"Name":"3"},{"Name":"8"}];
result = s.filter(a => !t.some(b => a.Name === b.Name));
console.log(result);
An approach using set and .filter method
var s=[
{
"Name": "1"
},
{
"Name": "2"
},
{
"Name": "3"
},
{
"Name": "4"
},
{
"Name": "5"
},
{
"Name": "6"
}
];
var t= [
{
"Name": "1"
},
{
"Name": "2"
},
{
"Name": "3"
},{
"Name": "8"
}
];
var set = new Set();
t.forEach(obj => set.add(obj.Name));
s=s.filter(obj => !set.has(obj.Name))
console.log(s);
z = f(s, t);
function f(first, second) {
var z = [];
for (var i = 0; i < first.length; i++) {
var included = false;
for (let j = 0; j < second.length; j++) {
if(equal(first[i], second[j]))
included = true;
//break; //optional
}
if(!included)
z.push(first[i]);
}
return z;
}
function equal(a,b){
//however you define the objs to be equal
return a.Name == b.Name;
}

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

How to make a JSON object out of a dictionary?

I'me new to JavaScript. In the browser I receive a long dictionary like this:
{"cat": "4" , "dog": "5", "fish": "9" }
I'm wondering what is the most efficient way to convert it to a JSON object like:
[
{
"name": "cat",
"value": "4"
},
{
"name": "dog",
"value": "5"
},
{
"name": "fish",
"value": "9"
}
]
You can Loop through it and push each key-value-pair to an Array.
var tValue = {"cat": "4" , "dog": "5", "fish": "9" };
var tList = [];
for(var tKey in tValue) tList.push({name: tKey, value: tValue[tKey]});
console.log(tList);
You can just loop over the dictionary object keys using Object.keys() method, and use .map() method to transform each iterated key/value pair to the appropriate object:
var results = Object.keys(obj).map(function(k) {
return {
name: k,
value: obj[k]
};
});
Demo:
var obj = {
"cat": "4",
"dog": "5",
"fish": "9"
};
var results = Object.keys(obj).map(function(k) {
return {
name: k,
value: obj[k]
};
});
console.log(results);
You can use the function Object.entries to get every key-value pairs and with the function map build the desired output.
let obj = {"cat": "4" , "dog": "5", "fish": "9" },
result = Object.entries(obj).map(([name, value]) => ({name, value}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can do this by this way :
Call a for in loop and read your first object
Push the name and the value in your new object one by one..
Sample code :
var a = {"cat": "4" , "dog": "5", "fish": "9" };
var newJSON = [] ;
console.log(a);
for ( key in a ) {
newJSON.push({name : key, value : a[key]});
}
console.log(newJSON);
You can have this kind of formatted object
{
animals : [
{"name":"cat", "value": 4},
{"name":"dog", "value": 5},
{"name":"fish", "value": 9}
]
}
or like this
[
{"name":"cat", "value": 4},
{"name":"dog", "value": 5},
{"name":"fish", "value": 9}
]

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

sort and pattern match an json

Am having a json like below,
[
{
"id": "1",
"freq": "1",
"value": "Tiruchengode",
"label": "Tiruchengode"
},
{
"id": "2",
"freq": "1",
"value": "Coimbatore",
"label": "Coimbatore"
},
{
"id": "3",
"freq": "1",
"value": "Erode",
"label": "Erode"
},
{
"id": "4",
"freq": "1",
"value": "Madurai",
"label": "Madurai"
},
{
"id": "5",
"freq": "1",
"value": "Salem",
"label": "Salem"
},
{
"id": "6",
"freq": "1",
"value": "Tiruchirappalli",
"label": "Tiruchirappalli"
},
{
"id": "7",
"freq": "1",
"value": "Tirunelveli",
"label": "Tirunelveli"
}
]
I need to pattern match it with label item in this json (ie), If I type tiru, then it has to result label items having tiru substrings in it.If its a single item array I know how to pattern match and sort it. Here am completely unaware that, how to pattern match using label item in the array. Is it possible to?. I need to do with Pure javascript, any help guys?
You can use the functional array methods introduced in JavaScript 1.6, specifically filter:
var search = 'tiru';
var results = obj.filter(function(item) {
var a = item.label.toUpperCase();
var b = search.toUpperCase();
return a.indexOf(b) >= 0;
});
If you wanted labels only, you can then use map to return only that property alone:
var labels = obj.filter(function(item) {
var a = item.label.toUpperCase();
var b = search.toUpperCase();
return a.indexOf(b) >= 0;
}).map(function(item) {
return item.label;
});
Essentially, filter is a method available to any Array which returns a new Array containing only those members for which the supplied function return true.
JSON.parse() will help convert the jsonString to JsonObject then just iterate the object use indexOf for pattern matching.
var jsonString = '[{"id": "1","freq": "1","value": "Tiruchengode","label": "Tiruchengode"},{"id": "2","freq": "1","value": "Coimbatore","label": "Coimbatore"},{"id": "3","freq": "1","value": "Erode","label": "Erode"},{"id": "4","freq": "1","value": "Madurai","label": "Madurai"},{"id": "5","freq": "1","value": "Salem","label": "Salem"},{"id": "6","freq": "1","value": "Tiruchirappalli","label": "Tiruchirappalli"},{"id": "7","freq": "1","value": "Tirunelveli","label": "Tirunelveli"}]';
var jsonObjects = JSON.parse(jsonString);
var pattern = "tiru";
for(var key in jsonObjects){
var label = jsonObjects[key].label.toUpperCase();
if(label.indexOf(pattern.toUpperCase()) != -1){
document.write(label+"<br/>");
}
}

Categories