How to delete an object from Javascript object - javascript

I'd like to delete an object element from an object. I have tried the following but it returns the same without deleting an element. jsfiddle. I am trying to delete clock object.
How can I delete it?
var position = '{"weather":{"id":"weather","x":0,"y":0,"width":12,"height":9},"google_calendar":{"id":"google_calendar","x":0,"y":10,"width":12,"height":9},"clock":{"id":"clock","x":0,"y":19,"width":3,"height":3},"todo":{"id":"todo","x":3,"y":19,"width":6,"height":4}}';
var name = "clock";
console.log(position);//before delete
delete position.name;
//delete position.name;
console.log(position);//after delete
I'd like to achieve this.
{"weather":{"id":"weather","x":0,"y":0,"width":12,"height":9},
"google_calendar{"id":"google_calendar","x":0,"y":10,"width":12,"height":9},
"todo":{"id":"todo","x":3,"y":19,"width":6,"height":4}}

First off position is a string, not an object.
Second off, position.name operates on the .name property. If you want to operate on the property whose name is in the name variable, then you use position[name], not position.name.
So, if you remove the quotes from the declaration of position or call JSON.parse() on it to make it into an object so it's this:
var position = {
"weather": {
"id": "weather",
"x": 0,
"y": 0,
"width": 12,
"height": 9
},
"google_calendar": {
"id": "google_calendar",
"x": 0,
"y": 10,
"width": 12,
"height": 9
},
"clock": {
"id": "clock",
"x": 0,
"y": 19,
"width": 3,
"height": 3
},
"todo": {
"id": "todo",
"x": 3,
"y": 19,
"width": 6,
"height": 4
}
};
Then, you can do this:
var name = 'clock';
delete position[name];
console.log(position);
And, that will end up deleting the clock property from your object.

var position = {
"weather": {
"id": "weather",
"x": 0,
"y": 0,
"width": 12,
"height": 9
},
"google_calendar": {
"id": "google_calendar",
"x": 0,
"y": 10,
"width": 12,
"height": 9
},
"clock": {
"id": "clock",
"x": 0,
"y": 19,
"width": 3,
"height": 3
},
"todo": {
"id": "todo",
"x": 3,
"y": 19,
"width": 6,
"height": 4
}
};
Below statement will do your job.
delete position["clock"]

Related

Filter nested array with objects given a certain ID

I need to get data from a nested array of objects, given an ID that I have.
I have been trying to get data from it so that I can pass it in to Angular Gridster 2, but even when using array.filter, I am struggling to get the results I want.
Data I start with:
[
{
"0": {
"cols": 15,
"id": "5-1564645705217",
"rows": 7,
"type": 0,
"x": 0,
"y": 0
},
"1": {
"cols": 15,
"id": "5-1564645705217",
"rows": 7,
"type": 1,
"x": 15,
"y": 0
},
"2": {
"cols": 15,
"id": "5-1564645705217",
"rows": 8,
"type": 2,
"x": 0,
"y": 7
},
"id": "1zk66HvI97C03751LNQm"
},
{
"0": {
"cols": 5,
"id": "5-1564545",
"rows": 7,
"type": 0,
"x": 0,
"y": 0
},
"1": {
"cols": 5,
"id": "5-1564545",
"rows": 7,
"type": 1,
"x": 15,
"y": 0
},
"id": "8gdfg897C03751LNQm"
}
]
I have an id (such as 1zk66HvI97C03751LNQm) and want to be able to fetch the contents so that I end up with:
[
{
"cols": 15,
"id": "5-1564645705217",
"rows": 7,
"type": 0,
"x": 0,
"y": 0
},
{
"cols": 15,
"id": "5-1564645705217",
"rows": 7,
"type": 1,
"x": 15,
"y": 0
},
{
"cols": 15,
"id": "5-1564645705217",
"rows": 8,
"type": 2,
"x": 0,
"y": 7
}
]
Using Array.prototype.find you can easily locate element you want (granted it will only return first found entry, so if your id can be non unique you should use filter instead) after which i remove id from the found object, and turn the rest of the data into desired format.
const data = [{"0": {"cols": 15, "id": "5-1564645705217", "rows": 7, "type": 0, "x": 0, "y": 0}, "1": {"cols": 15, "id": "5-1564645705217", "rows": 7, "type": 1, "x": 15, "y": 0}, "2": {"cols": 15, "id": "5-1564645705217", "rows": 8, "type": 2, "x": 0, "y": 7}, "id": "1zk66HvI97C03751LNQm"}, {"0": {"cols": 5, "id": "5-1564545", "rows": 7, "type": 0, "x": 0, "y": 0}, "1": {"cols": 5, "id": "5-1564545", "rows": 7, "type": 1, "x": 15, "y": 0}, "id": "8gdfg897C03751LNQm"}]
const searchId = "1zk66HvI97C03751LNQm";
const {id, ...elementFound} = data.find(({id})=> id === searchId) || {}; // skip id as unnecessary, return empty object in case of no entries matching search criteria
const elementParsed = Object.values(elementFound); // get values of other fields
console.log(elementParsed);

Check properties that changed since last interval in NodeJS

In nodeJS, let's say that I have a little setInterval:
setInterval(() => {
// ...
}, 50)
And it sends to client entities:
setInterval(() => {
socket.emit("entities", { ... })
}, 50)
Entities looks like this:
{
"0": {
"collisionRadius": 40,
"entityClass": "Prop",
"health": 100,
"maxHealth": 100,
"model": "Tree",
"position": {
"x": 1970,
"y": 1477
},
"uid": 0,
"damage": 10,
"dead": 0,
"height": 32,
"hits": [],
"interpolatedYaw": 0,
"slowed": 0,
"stunned": 0,
"timeDead": 0,
"width": 32,
"yaw": 0
},
"1": {
"collisionRadius": 40,
"entityClass": "Prop",
"health": 100,
"maxHealth": 100,
"model": "Tree",
"position": {
"x": 1240,
"y": 1866
},
"uid": 1,
"damage": 10,
"dead": 0,
"height": 32,
"hits": [],
"interpolatedYaw": 0,
"slowed": 0,
"stunned": 0,
"timeDead": 0,
"width": 32,
"yaw": 0
},
"2": {
"collisionRadius": 40,
"entityClass": "Prop",
"health": 100,
"maxHealth": 100,
"model": "Tree",
"position": {
"x": 2195,
"y": 2034
},
"uid": 2,
"damage": 10,
"dead": 0,
"height": 32,
"hits": [],
"interpolatedYaw": 0,
"slowed": 0,
"stunned": 0,
"timeDead": 0,
"width": 32,
"yaw": 0
}
}
How do I, at every interval, only send updated properties from the all entities, and if all the entity didn't change, only send true?
Received entities should look like this:
{
"0": true,
"1": {
"health": 99,
"position": {
"x": 1245, /** position and health changed, send them **/
"y": 1866 /** even if only the x changed, send y too **/
}
},
"2": true /** all the entity stayed the same, so send `true` **/
}

Array becomes an Integer after applying unshift on it

I have an Object like this:
{
"index": 0,
"name": "b1a042ff6-0c75-4af2-a9da-1a16f333baee_p0",
"category": "others",
"rawUrl": "https://firebasestorage.googleapis.com/v0/b/vrcam-dev-5a815.appspot.com/o/5ab4f2a0-88e9-4bf5-86b5-61b528be707f/panoramas/panorama_XTsagLoxbA.png?alt=media&token=68ef261e-0c5e-4bf0-aebc-ab845fcec01a",
"isTopLogo": false,
"origin": "https://firebasestorage.googleapis.com/v0/b/vrcam-dev-5a815.appspot.com/o/5ab4f2a0-88e9-4bf5-86b5-61b528be707f/panoramas/panorama_XTsagLoxbA.png?alt=media&token=68ef261e-0c5e-4bf0-aebc-ab845fcec01a",
"position": {
"x": 0,
"y": 0
},
"panoramaRotation": {
"x": 0,
"y": 0,
"z": 0
}
}
Which I want to unshift to an Array (it's cloned version) like this:
[{
"adjustedRawUrl": "",
"category": "others",
"createdAt": 1514432540000,
"cubemapReady": false,
"desktopUrl": "https://im.ages.io/BGOLielt?cors&w=513",
"floorplanRotation": 0,
"index": 0,
"is720": false,
"isTopLogo": false,
"mobileUrl": "https://im.ages.io/BGOLielt?cors&w=4096",
"name": "b1a042ff6-0c75-4af2-a9da-1a16f333baee_p0",
"objectId": "3c312986-0ef1-42fc-9068-46fc13a04b8f",
"panoramaRotation": {
"x": 0,
"y": 0,
"z": 0
},
"position": {
"x": 0,
"y": 0
},
"rawUrl": "https://firebasestorage.googleapis.com/v0/b/vrcam-dev-5a815.appspot.com/o/5ab4f2a0-88e9-4bf5-86b5-61b528be707f/panoramas/panorama_lPea0mIc6H.png?alt=media&token=9e1494ff-2525-42a6-a058-12c26560349a",
"stereoUrl": "",
"thumbnail": "https://im.ages.io/BGOLielt?cors&w=400",
"updatedAt": 1514432619000
}, {
"adjustedRawUrl": "",
"category": "others",
"createdAt": 1514432231000,
"cubemapReady": false,
"desktopUrl": "https://im.ages.io/FK9uiel2?cors&w=251",
"floorplanRotation": 0,
"index": 1,
"is720": false,
"isTopLogo": false,
"mobileUrl": "https://im.ages.io/FK9uiel2?cors&w=4096",
"name": "b1a042ff6-0c75-4af2-a9da-1a16f333baee_p0",
"objectId": "08e9197c-ab27-48d8-a48d-b33452fcfd11",
"panoramaRotation": {
"x": 0,
"y": 0,
"z": 0
},
"position": {
"x": 0,
"y": 0
},
"rawUrl": "https://firebasestorage.googleapis.com/v0/b/vrcam-dev-5a815.appspot.com/o/5ab4f2a0-88e9-4bf5-86b5-61b528be707f/panoramas/panorama_pMUnnhYmpH.png?alt=media&token=e422e4f1-389b-43b7-927b-022b31e37d61",
"stereoUrl": "",
"thumbnail": "https://im.ages.io/FK9uiel2?cors&w=400",
"updatedAt": 1514432619000
}]
This is how I'm doing it:
const newClonedArray = JSON.parse(JSON.stringify(array)).unshift(object)
To my shock the result wasn't an Array but an Integer: 3.
Why is this? And how to fix it?
array.unshift() returns length of the modified array. It does not create a new array instead modifies the existing array. Thus you do not need to use any assignment here.
var object ={
"index": 0,
"name": "b1a042ff6-0c75-4af2-a9da-1a16f333baee_p0",
"category": "others",
"rawUrl": "https://firebasestorage.googleapis.com/v0/b/vrcam-dev-5a815.appspot.com/o/5ab4f2a0-88e9-4bf5-86b5-61b528be707f/panoramas/panorama_XTsagLoxbA.png?alt=media&token=68ef261e-0c5e-4bf0-aebc-ab845fcec01a",
"isTopLogo": false,
"origin": "https://firebasestorage.googleapis.com/v0/b/vrcam-dev-5a815.appspot.com/o/5ab4f2a0-88e9-4bf5-86b5-61b528be707f/panoramas/panorama_XTsagLoxbA.png?alt=media&token=68ef261e-0c5e-4bf0-aebc-ab845fcec01a",
"position": {
"x": 0,
"y": 0
},
"panoramaRotation": {
"x": 0,
"y": 0,
"z": 0
}
}
var array = [];
array.unshift(object);
console.log(array);
The docs explain
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
Maybe instead of assigning the result of unshift, do
const newClonedArray = JSON.parse(JSON.stringify(array));
newClonedArray.unshift(object);

Browsing a complex JSON

first of all, excuse me for my English, I'm French.
I am coming to you because I have a problem. I would like help browsing a complex JSON object with a loop in Javascript (because it generates itself with JOINTJS) but I am not being able to do it. I can do it manually by json [ "cells"] ["7"] ["attrs"] ["text"] ["text"]. Here is an example of JSON for one element:
{"cells":[
{
"type":"basic.Image",
"position":{
"x":50,
"y":350
},
"size":
{
"width":100,
"height":50
},
"angle":0,
"id":"4a2802a8-0bd6-4d06-9343-921092a1decd",
"z":1,
"attrs":{
"text":{
"text":"230004",
"fill":"black"
},
"image":{
"xlink:href":"/uploads/documents/computer.png",
"width":100,
"height":50
}
}
}
]}
and parse JSON :
I would get the "text": "230004" (which changes depending on the item).
Thank you in advance for your help !
You can access the object like this: obj.cells[7].attrs.text.text, where obj is a variable holding the object.
Also note that as the cells property holds an array, you can loop through that array and get each individual value separately, like this:
var obj = {
"cells": [{
"type": "basic.Image",
"position": {
"x": 50,
"y": 350
},
"size": {
"width": 100,
"height": 50
},
"angle": 0,
"id": "4a2802a8-0bd6-4d06-9343-921092a1decd",
"z": 1,
"attrs": {
"text": {
"text": "230004",
"fill": "black"
},
"image": {
"xlink:href": "/uploads/documents/computer.png",
"width": 100,
"height": 50
}
}
}, {
"type": "basic.Image",
"position": {
"x": 50,
"y": 350
},
"size": {
"width": 100,
"height": 50
},
"angle": 0,
"id": "4a2802a8-0bd6-4d06-9343-921092a1decd",
"z": 1,
"attrs": {
"text": {
"text": "230005",
"fill": "black"
},
"image": {
"xlink:href": "/uploads/documents/computer.png",
"width": 100,
"height": 50
}
}
}, {
"type": "basic.Image",
"position": {
"x": 50,
"y": 350
},
"size": {
"width": 100,
"height": 50
},
"angle": 0,
"id": "4a2802a8-0bd6-4d06-9343-921092a1decd",
"z": 1,
"attrs": {
"text": {
"text": "230006",
"fill": "black"
},
"image": {
"xlink:href": "/uploads/documents/computer.png",
"width": 100,
"height": 50
}
}
}]
}
obj.cells.forEach(function(cell) {
console.log(cell.attrs.text.text);
});

Create Multiple dictionary from single single JSON response in javascript?

Suppose I have a JSON response from server with following structure
var data={
"Data1": {
"height": 39,
"weight": 62,
"shape": {
"length": 19,
"width": 72
},
"color": "#00ff00",
"radius": 9.5,
"color_srv": "#ffff00"
},
"Data2": {
"height": 0,
"weight": 40,
"shape": {
"length": 19,
"width": 72
},
"color": "#000000",
"radius": 2.5,
"color_srv": "#ff0000"
}
}
I want this data dictionary to split into two with certain data in one dictionary while maintaining the structure. For e.g.
var data_height = {
"Data1":{
"height": 39,
"shape": {
"length": 19,
"width": 72
},
"color": "#00ff00",
"radius": 9.5,
},
"Data2":{
"height": 0,
"shape": {
"length": 19,
"width": 72
},
"color": "#000000",
"radius": 2.5,
}
}
var data_weight = {
"Data1":{
"weight": 39,
"shape": {
"length": 19,
"width": 72
},
"color_srv": "#00ff00",
"radius": 9.5,
},
"Data2":{
"weight": 0,
"shape": {
"length": 19,
"width": 72
},
"color_srv": "#000000",
"radius": 2.5,
}
}
The above two dictionary serve different purpose, so after getting unified result how am i suppose to split that single data from back end into two different dictionaries.
edit
This is something I tried doing but it throws error
solution 1:
var serve={},live={};
for(d in data){
pname = d.split(':')[0];
serve['pname'].radius= data[d].radius;
serve['pname'].center= data[d].center;
serve['pname'].color= data[d].color_srv;
live['pname'].radius= data[d].radius;
live['pname'].center= data[d].center;
live['pname'].color= data[d].color;
serve['pname'].numbers= data[d].serving;
live['pname'].numbers= data[d].living;
serve['pname'].place= pname;
live['pname'].place= pname;
}
edit2
solution 2:
var serve={},live={};
for(d in data){
pname = d.split(':')[0];
serve['radius']= data[d].radius;
serve['center']= data[d].center;
serve['color']= data[d].color_srv;
live['radius']= data[d].radius;
live['center']= data[d].center;
live['color']= data[d].color;
serve['numbers']= data[d].serving;
live['numbers']= data[d].living;
serve['place']= pname;
live['plcae']= pname;
}
Both of the above solutions doesn't seems to work.
As Nina says, just clone the objects and remove the properties you don't need from each object. Here I've used reduce with an initial object with data_height and data_height properties.
var clone = function (obj) { return JSON.parse(JSON.stringify(obj)); }
var output = Object.keys(data).reduce(function (p, c) {
var obj = data[c];
p.data_height[c] = clone(obj);
delete p.data_height[c].weight;
delete p.data_height[c].color_srv;
p.data_weight[c] = clone(obj);
delete p.data_weight[c].height;
delete p.data_weight[c].color;
return p;
}, { data_height: {}, data_weight: {} });
OUTPUT
{
"data_height": {
"Data1": {
"height": 39,
"shape": {
"length": 19,
"width": 72
},
"color": "#00ff00",
"radius": 9.5
},
"Data2": {
"height": 0,
"shape": {
"length": 19,
"width": 72
},
"color": "#000000",
"radius": 2.5
}
},
"data_weight": {
"Data1": {
"weight": 62,
"shape": {
"length": 19,
"width": 72
},
"radius": 9.5,
"color_srv": "#ffff00"
},
"Data2": {
"weight": 40,
"shape": {
"length": 19,
"width": 72
},
"radius": 2.5,
"color_srv": "#ff0000"
}
}
}
DEMO

Categories