Convert Array of Object to Regular JavaScript Object - javascript

I have the following array objects
var stats = [
[0, 200,400], [100, 300,900],[220, 400,1000],[300, 500,1500],[400, 800,1700],[600, 1200,1800],[800, 1600,3000]
];
I would like to know how to convert it to the following JavaScript object.
var stats = [
{x:0, y:200,k:400}, {x:100, y:300,k:900},{x:220, y:400,k:1000},{x:300, y:500,k:1500},{x:400, y:800,k:1700},{x:600, y:1200,k:1800},{x:800, y:1600,k:3000}
];

Array.prototype.map is what you need:
stats = stats.map(function(x) {
return { x: x[0], y: x[1], k: x[2] };
});
What you describe as the desired output is not JSON, but a regular JavaScript object; if it were JSON, the key names would be in quotes. You can, of course, convert a JavaScript object to JSON with JSON.stringify.

You can use map()
var stats = [
[0, 200,400], [100, 300,900],[220, 400,1000],[300, 500,1500],[400, 800,1700],[600, 1200,1800],[800, 1600,3000]
];
stats = stats.map(function(el) {
return {
x: el[0],
y: el[1],
k: el[2]
};
});
console.log(stats);

Related

How to filter and transform object into two level object

I'm struggling with this problem.
I have this object below.
const originalData = {
"price1": 100,
"amount1": 17.46,
"price2": 500,
"amount2": 29,
"price3": 700,
"amount3": 40.74
}
I want a new object inside an array like this below.
const newData =[
{price:100, amount:17.46},
{price:500, amount:29},
{price:700, amount:40.74}
],
I've tried these methods - filter/map/reduce and googled problom for ages to reach to the result that I wanted.
but couldn't get it.
please tell me how I can solve this problem.
Assuming the numbers for the keys are consecutive, you can divide the amount of keys by 2 to get the number of objects and create the array using Array#map or Array.from with the keys of the same number.
const originalData = {
"price1": 100,
"amount1": 17.46,
"price2": 500,
"amount2": 29,
"price3": 700,
"amount3": 40.74
}
let res = [...Array(Object.keys(originalData).length/2)]
.map((_,i)=>({price: originalData[`price${i+1}`],
amount: originalData[`amount${i+1}`]}));
console.log(res);
You can simply achieve it by using this logic :
const originalData = {
"price1": 100,
"amount1": 17.46,
"price2": 500,
"amount2": 29,
"price3": 700,
"amount3": 40.74
};
const arr = [];
Object.keys(originalData).forEach((key, index) => {
if (originalData[`price${index+1}`]) {
const obj = {};
obj.price = originalData[`price${index+1}`]
obj.amount = originalData[`amount${index+1}`]
arr.push(obj);
}
});
console.log(arr);

javascript equivalent to [x for x in array]

Is there any operation in Javascript just like [x for x in array] in python?
For example, I'm using javascript to reading a json file where there're dozens of (key, value) pairs needed to be handled(or transformed into other format). And I thought working in this way is stupid:
let transformed = []
for (let key in json){
transformed = [ /* doing some transform*/ ]
}
Is there anything like:
let transformed = [
lambda function1(key), lambda function2(value) for key, value in json
]
Thanks in advance.
The rough equivalent of Python's list comprehension is Array.map:
const myArray = [1, 2, 3]
const transformed = myArray.map((item) => item + 1)
// [2, 3, 4]
But your example is not about an array, but about an Object with keys and values. In Python, this would be a dict, and you'd use a dict comprehension along the lines of {function1(key): function2(value) for key, value in my_dict.items()}.
In JavaScript, you can turn such an object into an array with Object.entries, then perform the map, and finally transform it back into an object using Object.fromEntries:
const myObject = { a: 1, b: 2 }
const transformed = Object.fromEntries(Object.entries(myObject)
.map(([key, value]) => [key + 'x', value + 1]))
// { ax: 2, bx: 3 }
Note that fromEntries is fairly new and you might need to add a polyfill for it.
You can use a code likes this. You must use a function that handle operation on current single item.
const words = ['hello', 'bird', 'table', 'football', 'pipe', 'code'];
const capWords = words.forEach(capitalize);
function capitalize(word, index, arr) {
arr[index] = word[0].toUpperCase() + word.substring(1);
}
console.log(words);
// Expected output:
// ["Hello", "Bird", "Table", "Football", "Pipe", "Code"]
First of all, javascript does NOT support Associative Arrays. If you are used to them in Python, PHP, and other languages you need to do a little workaround in JS to achieve the same functionality.
The most common way to simulate an associative array is using an object.
let testObject = {name: "Color", value: "Red"};
And then you push every object into an array so you end up with something like this:
let testArray = [{name: "Color", value: "Red"}, {name: "Color", value: "Blue"}];
Once you have this array consisting of objects, you can use map function to go through every object in the array and do whatever you want with it.
testArray.map((item, index) => {
console.log("The value of "+index+". item is: "item.value);
})
You can use Array.map() function. It work pretty like Array.forEach() function
const numbers = [1, 2, 3, 4, 5]
let newArray = numbers.map((element) => {
return element * 2
})
console.log(newArray) // excepted : [ 2, 4, 6, 8, 10 ]
It can be reduce using
const numbers = [1, 2, 3, 4, 5]
let newArray = numbers.map(element => element * 2)
console.log(newArray) // excepted : [ 2, 4, 6, 8, 10 ]
For more informations, you can this documentation https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Converting Array to object without any key or single key

I just want to create an object which contains all the values of an array on a sigle key .
arr1 = [{ x: 12, y:13},{ x1: 14, y2:15}];
arr2 = [{ xx: 18, yy:18},{ xx1: 17, yy2:16}];
// result = { finalObj :[{ x: 12, y:13},{ x1: 14, y2:15}],[{ xx: 18, yy:18},{ xx1: 17, yy2:16}]}
Although i can get final array by :
const finalArr = arr1.concat(arr2);
But how to get the end result .
Thanks in advance .
Concat two arrays
{ finalObj: [...arr1, ...arr2] }

Javascript: select array into new array (like C# Select)

In C# if I had a list for example of 3 ints [1,2,3], I could trasform that list into another with .Select in following way [1,2,3].Select(e => new { Id = e, Name = $"name:{e}"), which would return new array with 3 objects.
how can I get the same result in js without using for loop?
You can use the map function like this:
var array = [1,2,3]
var result = array.map(e => ({id: e, name: `name:${e}`}))
console.log(result)
It returns the following result:
[ { id: 1, name: 'name:1' },
{ id: 2, name: 'name:2' },
{ id: 3, name: 'name:3' } ]
Here is the map function docs:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Yes, it is called map(example with integers, but you can map into objects too):
const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]

Merging or appending array of objects in different object

I am using angularjs where I have a $scope.var1 ={a:10, b:20, c:30}; in which I want to append another value(s) which is infact an array of objects i.e. $scope.myobjects=[{m:10, n:30}, {x:6, y:8}, ....]; after appending this value my $scope.var1 should look like, $scope.var1={a:10, b:20, c:30, m:10, n:30, x:6, y:8};
any idea please.
Thanks
obj ={a:10, b:20, c:30};
arr=[{m:10, n:30}, {x:6, y:8}];
arr.forEach(function(a){
Object.keys(a).forEach(function(key){
obj[key]=a[key];
})
})
console.log(obj);
You could iterate the array and use Object.assign.
The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.
If not on the user agent available, like on IE, you could use a polyfill.
var target = { a: 10, b: 20, c: 30 };
objects = [{ m: 10, n: 30 }, { x: 6, y: 8 }];
objects.forEach(function (o) {
Object.assign(target, o);
});
console.log(target);
Object.assign.apply(null, [$scope.var1].concat($scope.myobjects))
Please try this one:
var var1 = { a: 10, b: 20, c: 30 };
myobjects = [{ m: 10, n: 30 }, { x: 6, y: 8 }];
myobjects.forEach(function (o) {
for (var p in o) {var1[p] = o[p]};
});
console.log(var1);
Note that this code simply add/update properties based on source object

Categories