Generate new json data after applying math in older json data - javascript

I want to generate new json data from my older json data after applying some maths. I want to apply some simple maths as well as some javascript math functions liek sin,cos to the second series of the json data and get the output in the new json array. I have tried a code for it please take a look.
var data = [{a:1, b:321}, (a:2, b:432), {a:3, b:423}]
jsonObj.result.b.toFixed(4) = data.jsonObj.b + 100 * math.sin(45);
var newjsonfile = [{data.jsonObj.a, jsonObj.resilt.b}]
console.log(newjsonfile);
// result should be like
// [{a:1, b:0.0265}, (a:2, b:-0.8776), {a:3, b:0.8218}]

You need map(), example:
const data = [
{ a: 1, b: 321 },
{ a: 2, b: 432 },
{ a: 3, b: 423 },
];
const newData = data.map(d => ({ ...d, b: (d.b + 100 * Math.sin(45)).toFixed(4) }));
console.log(newData);

Related

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

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]

JavaScript: Find in array all values with substrings of array

I have two arrays; one with substrings and the other with objects.
I would like to obtain an array of objects where those objects contain any of the substrings in the substrings array.
So far I have tried to use filter and findIndex. Each approach works if a substring is identical. In this case, even indexOf was not working. I am not javascript guy, so probably I am doing something wrong.
Script
var strings = ['12', 'sv', 'eli', '23', '34'];
var data = [
{
a: 349531284734,
b: "sv123eippppppeli",
c: "aaabbbccc"
},
{
a: 1111123333312,
b: "ccccccccccccs2222",
c: "aaabbbccc"
},
{
a: 2222234,
b: "elllllllla",
c: false
},
];
// attempt 1
var results = data.filter(arr =>
Object.keys(arr).some(key => {
return String(arr[key]).toLowerCase().includes(strings) // or indexOf
})
);
// attempt 2 with only one data index
var obj = Object.values(data[0]);
var results = strings.some(s => obj.includes(s)) // or indexOf or findIndex;
Explanation
In this example with the given substrings, only data[0] is a match because it contains at least on of the substrings in the strings array.
How can I make this work without using a "for loop"?
Thanks
A simple solution that avoids the need for "for-loop" syntax would be to filter() each object of data by a predicate that checks if any value (of the current item being filtered) contains any one of the values of the strings array.
In code, this can be expressed as:
var strings = ['12', 'sv', 'eli', '23', '34'];
var data = [{
a: 349531284734,
b: "sv123eippppppeli",
c: "aaabbbccc"
},
{
a: 1111123333312,
b: "ccccccccccccs2222",
c: "aaabbbccc"
},
{
a: 2222234,
b: "elllllllla",
c: false
},
];
// Local helper retruns true if case-insenstive value in strings array
const stringHasValue = (value) => strings
.some(str => value.toLowerCase().includes(str.toLowerCase()))
// Filter each item in data array by existance of a value containing
// substring in strings array
var result = data.filter((item) => Object.values(item)
.filter(value => typeof value === 'string')
.some(stringHasValue, []));
console.log(result);

Trouble using javascript partial.lenses to obtain properties within an array

I'm trying to figure out how to create a lens that'll give me an array of the key values from within an array. Here's a simple example:
const L = require('partial.lenses');
const data = [
{
r: [
{
d: {
one: 1,
two: 2
}
}
]
},
{
r: [
{
d: {
three: 3,
four: 4
}
}
]
}
];
const lens = L.compose (
L.elems,
L.prop ('r'),
L.elems,
L.prop ('d'),
);
const result = L.get (lens, data);
console.log (result);
I want:
[{ one: 1, two: 2 }, { three: 3, four: 4 }]
But get:
{ one: 1, two: 2 }
I'm sure this is trivial, but can't get it quite right. Once my lens correctly selects the array of 'd's I want to use L.modify to get the data with all of the 'd' objects replaced with a string. I think I know how to do once my lens is correct.
Thanks
Use L.collect instead of L.get, L.get returns the first found entity, while L.collect returns all matching entities, similar to [].filter vs [].find.
https://github.com/calmm-js/partial.lenses#l-collect

Parse.com retrieving value of nested object

Lets say i have object like this:
var a = {
b: {
c: 1,
d: 2
}
}
And i have saved this object in Parse backend. There are 100 objects, but with different c and d values. Can i do search searching only objects which contains d:2. Or the only way is to query all objects and then use for loop which will search for d:2?
Dont read this!
Writting this line just to get posted, because system does not allow to post me question, dont know why
Thank you
Update
Maybe i am not clear enough, I am using parse.com you can retrieve objects by using this line:
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.equalTo("playerName", "Dan Stemkoski");
query.find();
If anybody knows if you can retrieve objects with specific values in nested objects, that would be great.
You can do something like this
var a = {
b0: {
c: 1,
d: 2
},
b1: {
c: 5,
d: 3
},
b2: {
c: 1,
d: 4
},
b3: {
c: 2,
d: 2
},
b4: {
c: 1,
d: 4
},
b5: {
c: 7,
d: 2
},
},
d2s = Object.keys(a).filter(e => a[e].d == 2).map(e => a[e]);
document.write("<pre>" + JSON.stringify(d2s,null,2) + "</pre>");

Categories