I am trying to write a function that can take a field name as an argument and return an array of corresponding values from a bit of JSON.
Example object:
var myObject = [
{"x": 10, "y": 10},
{"x": 20, "y": 10},
{"x": 20, "y": 20},
{"x": 10, "y": 20}
];
My function looks something like this:
function getValues(desiredValue) {
var values = [];
for (i = 0; i < myObject.length; i++) {
values[i] = myObject[i].desiredValue;
}
return values;
}
getValues(x);
Ideally, I would have the argument x passed to the getValues which, instead of looking for a field name called desiredValue would look for a field name called x.
The returned array should look like this:
[10,20,20,10]
As the problem with this code is obvious, how can I get the desired result?
Also, I am trying to avoid unnecessary dependencies, so please don’t give me any JQuery unless absolutely necessary.
You can use map() to return desired result.
var myObject = [
{"x": 10, "y": 10},
{"x": 20, "y": 10},
{"x": 20, "y": 20},
{"x": 10, "y": 20}
];
function getValues(desiredValue) {
return myObject.map(e => e[desiredValue]);
}
console.log(getValues('x'))
You actually need to parse the given JSON string (not the array that you have given here) by using JSON.parse(). See: http://jsbin.com/kevoqe/edit?js,console
a simple utility
//also accepts a path like "foo.bar.baz"
//returns undefined if path can't be resolved
function fetch(path){
var keys = path.split(".");
return function( target ){
for(var t = target, i = 0; i < keys.length; t = t[ keys[ i++ ] ])
if(t == null) return void 0;
return t;
}
}
and it's usage
var myObject = [
{"x": 10, "y": 10},
{"x": 20, "y": 10},
{"x": 20, "y": 20},
{"x": 10, "y": 20}
];
var result = myObject.map( fetch("y") );
this version is a bit more flexible than one hardwired with Array.map() because it can easily be composed with other functions.
Although, especially in this particular case, this already is a little bit of overkill. here you can easily write:
var result = myObject.map(pt => pt.y);
you can't get any shorter and simpler. Or if for some reason the property really is dynamic, you'll have some variable containing it:
var dynamicPropertyName = "y";
//...
var result = myObject.map(pt => pt[ dynamicPropertyName ]);
Use array map method to do manipulation in an array of objects.
Try this code :
var myObject = [
{"x": 10, "y": 10},
{"x": 20, "y": 10},
{"x": 20, "y": 20},
{"x": 10, "y": 20}
];
var output = getValues("x");
console.log(output);
function getValues(desiredValue) {
return myObject.map(function(item) {
return item[desiredValue];
});
}
Output :
Working fiddle : https://jsfiddle.net/ffyjyzjb/
Related
I have an array of Vector3 that will make up/draw a path.
From every point onwards I want to see which direction the next point will be. Straight or left or right if the angle is steep enough.
What I tried
I creating an Object3D on every vector of the array and then pointing that (with lookAt) to the next vector. But the rotation of the tempObject is NaN when I do.
I created two Object3D to get the second object's world position.
What I expect
I want to store the angle in radians or degrees of every Object3D to determine its direction.
const path = [
{ "x": -2.47, "y": 0, "z": 7.61 },
{ "x": -2.14, "y": 0, "z": 6.63 },
{ "x": -1.09, "y": 0, "z": 2.33 },
{ "x": -1.06, "y": 0, "z": 0.8 },
{ "x": -1.83, "y": 0, "z": 0.71 },
{ "x": -9.12, "y": 0, "z": 0.39 },
{ "x": -9.48, "y": 0, "z": -0.66 }
];
if (path.length > 2) {
let index = 0;
const pathSegments = Math.floor(path.length / 2);
for (let i = 0; i<pathSegments; i++) {
const v1 = path[index];
const v2 = path[index+1];
// Fake object
const tempObject = new THREE.Object3D();
tempObject.position.set(v1);
tempObject.lookAt(v2);
console.log(tempObject.rotation);
}
}
I might be going about this the wrong way. Any help or points would be great!
The objects in your path array have to be of type THREE.Vector3. Beside, Vector3.set() does not accept an instance of THREE.Vector3 as an argument. So use the following or THREE.Vector3.copy():
tempObject.position.set(v1.x, v1.y, v1.z);
This should solve the NaN issue.
I am having trouble reformatting an Object array in Javascript. I have an array that looks like this:
[
{
"deviceid": 42,
"x": "2022-03-26T00:00:18",
"y": 17.8,
},
{
"deviceid": 42,
"x": "2022-03-26T00:01:18",
"y": 17.8,
},
{
"deviceid": 43,
"x": "2022-03-26T00:02:18",
"y": 17.8,
{
"deviceid": 43,
"x": "2022-03-26T00:02:18",
"y": 17.8,
}]
I want to re-shape it so the new form will be one record per device id and all x and y values in the same row.
[
{
"deviceid": 42,
"x": ["2022-03-26T00:00:18","2022-03-27T00:00:18"],
"y": [17.8, 15.6],
},
{
"deviceid": 43,
"x": ["2022-03-26T00:01:18","2022-03-27T00:00:18"],
"y": [17.8, 19.1],
}]
How can I make this happen?
You can use reduce() to do the reduction of your values using a JavaScript object. After the reduction get the values of the object using Object.values().
const data = [
{
deviceid: 42,
x: "2022-03-26T00:00:18",
y: 17.8,
},
{
deviceid: 42,
x: "2022-03-26T00:01:18",
y: 15.6,
},
{
deviceid: 43,
x: "2022-03-26T00:02:18",
y: 17.8,
},
{
deviceid: 43,
x: "2022-03-26T00:02:18",
y: 19.1,
},
];
const result = data.reduce((devices, device) => {
// check if we have encountered this decive before using the deviceId
if (!devices.hasOwnProperty(device.deviceid)) {
// we have not: create an key-value pair using device ID as key and device info as value
// use an array for x and y
devices[device.deviceid] = {
deviceId: device.deviceid,
x: [device.x],
y: [device.y],
};
} else {
// we have seen this device before
// get the device value using the key (deviceId) and push new x and y values to it
const curDev = devices[device.deviceid];
curDev.x.push(device.x);
curDev.y.push(device.y);
}
// return JS object of devices for next iteration/ result
return devices;
}, {});
console.log(Object.values(result));
Please note: I think the input you have provided in your question contains some errors probably from copy/ pasting as the expected output contains values that are not in the input at all. I have changed values of y in the input to show you that output is actually what you expect.
I've created a JavaScript extension for my Jupyter Notebook that will plot some data for me. Right now I have the data hardcoded within the extension.
My question: is there a way to access a data object that exists within the Notebook?
For example, below is some sample code for an extension:
define([
'base/js/namespace'
], function(
Jupyter
) {
function test_second_extension() {
var handler = function () {
console.log(
'This is the current notebook application instance:',
Jupyter.notebook
);
var data = [{"x": 1, "y": 5}, {"x": 2, "y":12}, {"x": 3, "y": 27}];
console.log(data);
};
var action = {
icon: 'fa-comment-o', // a font-awesome class used on buttons, etc
help : 'Print notebook instance',
help_index : 'zz',
handler : handler
};
var prefix = 'test_second_extension';
var action_name = 'show-alert';
var full_action_name = Jupyter.actions.register(action, action_name, prefix); // returns 'my_extension:show-alert'
Jupyter.toolbar.add_buttons_group([full_action_name]);
}
return {
load_ipython_extension: test_second_extension
};
});
And this is what I have in a Python3 Jupyter cell:
import pandas as pd
data = pd.read_json('[{"x": 1, "y": 5}, {"x": 2, "y":12}, {"x": 3, "y": 27}]')
Is there a way to access the data object that is created in the Jupyter cell from within the extension, instead of hardcoding it?
A bit janky but try this
from IPython.core.display import Javascript
import json
#list of dicts
list_of_dicts = [{"x": 1, "y": 5}, {"x": 2, "y":12}, {"x": 3, "y": 27}]
#convert to json string
json_list = json.dumps(list_of_dicts)
#run in cell
#This will run in the console check your browser
Javascript("""
var json_list = {};
window.variable = json_list;
console.log(json_list);""".format(json_list))
#or as a function
#replace console_log with what you need
def run_in_console(data):
json_list = json.dumps(data)
return Javascript("""
var json_list = {};
window.variable = json_list;
console.log(json_list);""".format(json_list))
This question already has answers here:
Javascript Console Log reporting object properties incorrectly
(1 answer)
Weird behavior with objects & console.log [duplicate]
(2 answers)
Closed 5 years ago.
I've got the following code:
$(document).ready(function(){
var array = [{"x": 0}];
array[0] = {"x": 10};
console.log(array);
array[0] = {"x": 20};
console.log(array);
});
With this I expect the output in the console to be:
[
{
0: {"x": 10}
}
]
[
{
0: {"x": 20}
}
]
But instead it is:
[
{
0: {"x": 20}
}
]
[
{
0: {"x": 20}
}
]
Does anyone have any idea why? Am I missing something?
JSFiddle: https://jsfiddle.net/6nfdmt91/
try:
$(document).ready(function(){
var array = [{"x": 0}];
array[0] = {"x": 10};
console.log(array);
array[0].push({"x": 20});
console.log(array);
});
Using Array.push() will "push" a new element.
I'm using jqPlot and I need to turn this JSON which I receive from a WCF service:
[{ "x": 2, "y": 3 }, { "x": 25, "y": 34 }]
into this array or arrays:
[[2,3],[25,34]]
I've tried JSON.parse & eval but to no avail.
thanks
You can use $.map() to do that:
var data = [{ "x": 2, "y": 3 }, { "x": 25, "y": 34 }]
var flattenedResult = $.map(data, function(point) {
return [[ point.x, point.y ]];
});
Parse the string into an array of objects:
var json = '[{ "x": 2, "y": 3 }, { "x": 25, "y": 34 }]';
var o = $.parseJSON(json);
Then replace each object in the array with an array:
for (var i=0; i<o.length; i++) o[i] = [o[i].x, o[i].y];