Convert Js Array to JSON object with keys - javascript

I want to use the same object for jQplot and a library built on jQtable.
jQplot is fine with arrays but jQtable's library needs an named object (dictionary).
vals =
[
[1, 2],
[3,5.12],
[5,13.1],
[7,33.6],
[9,85.9],
[12,54],
[11,219.9]
];
This is my js array
I want it to be like
{
data: [{
X: 1,
Y: 2
},
{
X: 3,
Y: 5.12
},
{
X: 5,
Y: 13.1
}]
}
How to convert js array into named JSON array of objects? Are there any built in methods or I define my own method to read up that array and create a String for JSON?

var array = vals.map(function(val) {
return {
X : val[0],
Y : val[1]
};
});

var data = Object.keys(vals).map(function(key) {
return {X : vals[key][0], Y : vals[key][1]};
});

Related

Use reduce to remove object in an array

I am trying to return an array that contain of one of property.
So there is an array of objects like
[{x: 5, y: 607, width: 782, height: 602, line_width: 3, …},
{x: 10, y: 602, width: 772, height: 592, line_width: 3, …},
{x: 0, y: 400, size: 18, text: 'This cer..}, ..]
Some object has section: 'TextInstruction' property defined and some do not.
I am trying to return an array that is only containing section with no duplicate and no undefined.
So return ['TextInstruction', 'RectangleInstruction', ...]
No [undefined, 'TextInstruction', 'TextInstruction', ...]
Can anyone help me with JavaScript to get this using reduce() function?
You can try this:
var objectArray = {someting....}; // Your Object Array
var indexOfObject = objectArray.findIndex(object => {
return object.section == null;
});
objectArray.splice(indexOfObject, 1);
You don't need reduce to do that. You can do it with filter and map.
myArray
// filter missing sections
.filter(a => a.section)
// map to array of sections
.map(a => a.section)
// filter unique
.filter((a, i, arr) => arr.indexOf(a) === i)
The reduce() way of doing it could be something like this:
const data=[{a:12,b:45,section:"first"},{section:"second",d:5,f:7},{x:23,y:78,height:200},{a:445,x:34,section:"first"}];
const res1=Object.keys(data.reduce((a,c)=>{
if(c.section) a[c.section]=1;
return a;
}, {}));
// Or, using the es6 Set object:
const res2=[...data.reduce((a,c)=>{
if(c.section) a.add(c.section);
return a;
}, new Set())];
// show results:
console.log(res1,res2);
The second approach makes sense when the values to be collected are objects (and not only strings).

How to insert a object in an array (as a element )

I am from C++ background.
I am trying to translate a C++ code to JavaScript.
in C++ we have vector < pair < int,int > > to store pairs.
in JS i have a situation. i want to store 2D coordinates. i actually want to push new coordinates to the array.
i did like
first I created a Object
const coordinate = {
x= 9,
y= 10
}
Then i tried to push that object into the array CoordinateStorage that i want this object to get stored
CoordinatesStorage.unshift({X : coordinate.x, Y : coordinates.y});
I know this code shown above is absolutely wrong to store an object into the array. I searched out for sources but i got nothing useful.
Please recommend some sources that i can refer for such translation related problems if possible.
Generally speaking, we should use the .push method for an array.
There are other methods available you can find them here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array but the .push method for your case is more suitable.
Basically, as a result, we want to have something like this:
[ {x: 2, y: 4 }, { x: 2, y: 4 } ] We have an array of objects.
Or we could also have an array of arrays:
[[1, 2], [3, 4], [4, 6]] Not sure if it okay for your case, but maybe as an option.
Also, we could create a class Vector and we might have something like
[ Vector { x: 1, y: 2 }, Vector { x: 3, y: 4 }, Vector { x: 4, y: 6 } ]
Let's take a look at the examples:
Using the plain object for the vector:
const coordinate1 = {
x: 2,
y: 4
};
const coordinate2 = {
x: 3,
y: 4
};
const coordinatesStorage = [];
coordinatesStorage.push(coordinate1);
coordinatesStorage.push(coordinate2);
If you will do console.log(coordinatesStorage) you will see [ { x: 2, y: 4 }, { x: 3, y: 4 } ]
Using the array to store a vector:
const coordinate1 = [1, 2];
const coordinate2 = [3, 4];
const coordinatesStorage = [];
coordinatesStorage.push(coordinate1);
coordinatesStorage.push(coordinate2);
The coordinatesStorage will be [ [ 1, 2 ], [ 3, 4 ] ]
Using the Vector class:
Maybe in your case, it would be more helpful to operate with a class Vector:
class Vector {
constructor(x, y) {
this.x = x;
this.y = y;
}
}
const coordinatesStorage = [];
coordinatesStorage.push(new Vector(1, 2));
coordinatesStorage.push(new Vector(3, 4));
coordinatesStorage.push(new Vector(4, 6));
And here in the console you will see [ Vector { x: 1, y: 2 }, Vector { x: 3, y: 4}, Vector { x: 4, y: 6 } ]
Take a look at the Vector implementations in JS:
https://gist.github.com/jjgrainger/808640fcb5764cf92c3cad960682c677
https://github.com/maxkueng/victor/blob/master/index.js
I hope this helps. Good luck!
First initialize the array
var CoordinatesStorage = [];
//create object
const coordinate = {
x: 9, // Note - the operator is colon : not = as in the question
y: 10
}
// push to array
CoordinatesStorage.push(coordinate);
Now your array will be like this [{x:9, y:10}] if you push again the array will be [{x:9, y:10}, {x:9, y:10}]
Tip: Arrays are denoted by square brackets eg: ['math', 'science', 'english']
Objects are denoted by key-value pairs wrapped in curly brackets
eg: var student = {
name: "John", // string value
age: 6, // integer value
sex: "M",
phone: [123456789 , 564654654] // value is of array of 2 items
}

Add Key To Javascript Array

I'm looking to append keys to the array which I have created, so I have an array of numbers:
var Array1 = [1, 2, 3, 4, 5];
I want to convert the array so it looks like this:
Array1 = [{ x: 1 }, { x: 2 }, { x: 3 }, { x: 4 }, { x: 5 }];
How do I append to each value in the array like so?
https://www.sitepoint.com/a-beginners-guide-to-data-binding-in-d3-js/ - Within this article, we can see they have an array called 'Data' - An array of objects. Now I have a simple array full of numbers and I need it to be converted as described above
You could use Array#map together with short hand properties for a new object for each element of the array.
var array = [1, 2, 3, 4, 5],
objects = array.map(x => ({ x }));
console.log(objects);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Array1 = Array1.map(entry => ({x: entry}));

Compare 2 array using lodash

I have 2 arrays of similar element but arranged in different order.
I have a source variable with is arranged according to arr1 based on key src and file of arr1 and source.
Now i want to arranged destination variable according to arr2.
Could you please let me know how we can done with lodash?
arr1 = [{x:0,y:1,src:a1},{x:1,y:1,src:b1},{x:2,y:1,src:c1}]
arr2 = [{x:1,y:1,src:b1},{x:1,y:1,src:a1},{x:1,y:1,src:c1}]
source = [{file:a1},{file:b1},{file:c1}]
Destination = [{file:b1},{file:a1},{file:c1}]
You could use lodash's map routine to achieve this:
let source = [{
x: 1,
y: 1,
src: 'b1'
}, {
x: 1,
y: 1,
src: 'a1'
}, {
x: 1,
y: 1,
src: 'c1'
}]
let destination = _.map(source, value => {
return { file: value['src']}
})
See here for an example.
Also note that you can achieve this using the standard JavaScript map function.

How to transform an array into a new array [duplicate]

This question already has answers here:
Changing the key name in an array of objects?
(11 answers)
Closed 5 years ago.
How can I transform values from an array to a new array?
I have an array like:
[
{ "amount" : 10, "date" : "2017-05-30" }...
]
which I want to "transform" into
[
{ x : 10, y: 2017-05-30 }
]
any help is appreciated...
You could map new objects with the new properties.
var array = [{ amount: 10, date: "2017-05-30" }],
newArray = array.map(a => ({ x: a.amount, y: a.date }));
console.log(newArray);
Using Array#map()
The callback function will create a new object with the 2 properties needed. You just have to keep the value of the current array
const array = [{ "amount" : 10, "date" : "2017-05-30" }];
let newArray = array.map(_=>({x:_.amount,y:_.date}));
console.log(newArray);
You can try using lodash map Lodash map
It will be something like:
const array2 = _.map(array1, (item) => { x: item.amount, y: item.date });

Categories

Resources