How to call those who have more data? json - javascript

Good day, as I can call from an array of a json those that contain more data, I am creating a graph and must contain those with more data, I have this code where I send my data
vehiculoPorColores = () => {
const _this = this
fetch("/live/graph/color")
.then(response => response.json())
.then(datos => {
const vehicleKey = Object.keys(datos)
console.log(vehicleKey)
_this.setState(
{
vehiculosC: vehicleKey.splice(0, 5).map((i, e) => ({
name: vehicleKey[e],
colores: datos[i]
}))
},
() => {
setTimeout(this.vehiculoPorColores, 1000)
}
)
})
}
JSON:
{
"lavender": 3,
"white": 12,
"dimgrey": 4,
"seagreen": 2,
"lightslategrey": 6,
"slategrey": 7,
"indianred": 2,
"snow": 1,
"darkslategrey": 1,
"khaki": 1,
"gainsboro": 3,
"palevioletred": 1,
"darkgrey": 1
}
to be more specific: json
I need to sort the data and choose the 5 records with the highest values, right now I only send a call to 5 but they are not the ones that have more data, and I need that and that they are only 5, aahh and I work in react

If you want to sort an array in JS you can do...
Having an object shaped as:
{
key1: 10,
key2: "a string"
}
Then having an array:
[{
key1: 10,
key2: "a string"
},
{
key1: 20,
key2: "a string"
}]
You can do this:
[{
key1: 10,
key2: "a string"
},
{
key1: 20,
key2: "a string"
}].sort((elemN, elemNplus)=> elemN.key1 - elemNplus.key1) :: output => [{
key1: 10,
key2: "a string"
},
{
key1: 20,
key2: "a string"
}]
and Greater first:
[{
key1: 10,
key2: "a string"
},
{
key1: 20,
key2: "a string"
}].sort((elemN, elemNplus)=> elemNplus.key1 - elemN.key1) :: output => [{
key1: 20,
key2: "a string"
},
{
key1: 10,
key2: "a string"
}]

Related

How to get the number difference between two or more objects in an array?

So for example I have an array as such:
const obj = [
{
key1: 3,
key2: 5,
key3: 6,
},
{
key1: 2,
key2: 3,
key3: 4,
},
{
key1: 6,
key2: 5,
key3: 5,
}
]
I want to be able to get the difference between the objects as such:
// RESULT
[
// Object filled with difference of obj[1] - obj[0]
{
key1: -1,
key2: -2,
key3: -2,
},
// Object filled with difference of obj[2] - obj[1]
{
key1: 4,
key2: 2,
key3: 1,
}
]
Is there a way I can achieve this?
I was able to find a snippet of code as such but this only find the difference of elements in an array not an object.
var arr = [23, 53, 66, 11, 67]
const elementDifferenceArray = (arr) => {
const differenceArray = [];
for (let i = 1; i < arr.length; i++) {
differenceArray.push(Math.abs(arr[i] - arr[i - 1]));
};
return differenceArray;
}
console.log(elementDifferenceArray(arr));
You could get the keys and map new keys with delta of the array and a sliced array.
const
array = [{ key1: 3, key2: 5, key3: 6 }, { key1: 2, key2: 3, key3: 4 }, { key1: 6, key2: 5, key3: 5 }],
keys = Object.keys(array[0]),
result = array
.slice(1)
.map((o, i) => Object.fromEntries(keys.map(k => [
k,
o[k] - array[i][k]
])));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
const obj = [
{
key1: 3,
key2: 5,
key3: 6,
},
{
key1: 2,
key2: 3,
key3: 4,
},
{
key1: 6,
key2: 5,
key3: 5,
}
];
const differences = [];
for(var i= obj.length -1; i > 0; i--) {
var j = i - 1;
differences.push({
key1: obj[i].key1 - obj[j].key1,
key2: obj[i].key2 - obj[j].key2,
key3: obj[i].key3 - obj[j].key3,
});
};
const result = differences.reverse();

Get a one-dimensional array from an array of objects [duplicate]

This question already has answers here:
Convert array of objects to array of values [closed]
(2 answers)
Closed 1 year ago.
I have the following array of objects:
const input = [
{ key1: 1, key2: 1, key3: 5 },
{ key1: 2, key2: 5, key3: 6 },
{ key1: 4, key2: 6, key3: 7 },
{ key1: 7, key2: 8, key3: 9 },
];
I just want to loop through an array of objects and collect all the values ​​into a one dimensional array like this:
const output = [1, 1, 5, 2, 5, 6, 4, 6, 7, 7, 8, 9];
Can someone help solve this problem?
If the keys are always in that order, you can use Object.values as a callback to flatMap
const output = input.flatMap(Object.values)
const input = [
{ key1: 1, key2: 1, key3: 5 },
{ key1: 2, key2: 5, key3: 6 },
{ key1: 4, key2: 6, key3: 7 },
{ key1: 7, key2: 8, key3: 9 },
];
const output = input.flatMap(Object.values)
console.log(output)
Relying the order of keys in an object is generally NOT a good idea. You can destrcuture all the properties you need and flatten them in that order:
input.flatMap(({ key1, key2, key3 }) => [key1, key2, key3])
or
Create an array of keys to make it a bit more dynamic:
const keys = ["key1", "key2", "key3"]
const output = input.flatMap(o => keys.map(k => o[k]))

Merge multiple arrays of objects into one array of objects JavaScript

So suppose I have a few different Arrays as follows:
var first = [{key1: x},{key1:y},{key1:z},{key1:a},{key1:b},{key1:v}, ...];
var second = [{key2: anything},{key2:...},{key2:...},{key2:...},{key2:...},{key2:...}, ...];
var third = [{key3: value},{key3:...},{key3:...},{key3:...},{key3:...},{key3:...}, ...];
var fourth = [{key4:another value},{key4:...},{key4:...},{key4:...},{key4:...},{key4:...}];
var fifth = [{key5: and another one},{key5:...},{key5:...},{key5:...},{key5:...},{key5:...}];
.
.
.
and so on...
now I would like to merge them into one array where my new objects contain one of each of the other arrays like so:
var newBigArray = [{key1: x, key2: anything, key3: value, key4: another value, key5: and another one (here in this object the first of each of the original array's objects merged into one},{here in the second object the second of each of the original array's objects...},{here the third...},{fourth},{fifth},{...},...];
I hope you get the idea.
I have tried the .push() method, the Object.assign(), and some variations of for-loops but I can't find the solution.
How would one go about this, any ideas?
You could collect all objects in an array and assign all properties of the same index to a single object.
const
first = [{ key1: 'a' }, { key1: 'b' }, { key1: 'c' }, { key1: 'd' }, { key1: 'e' }, { key1: 'f' }],
second = [{ key2: 1 } , { key2: 2 }, { key2: 3 }, { key2: 4 }, { key2: 5 }, { key2: 6 }],
third = [{ key3: 'z' }, { key3: 'y' }, { key3: 'x' }, { key3: 'w' }, { key3: 'v' }, { key3: 'u' }],
result = [first, second, third]
.reduce((r, a) => a.map((o, i) => Object.assign(r[i] || {}, o)), []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use the spread operator:
let first = [{x: 1, y:2}]
let second = [{x: 2, y:2}]
let third = [{x: 3, y:2}]
let fourth = [{x: 4, y:2}]
let fifth = [{x: 5, y:2}]
let finalArray = [
...first,
...second,
...third,
...fourth,
...fifth
]
console.log(finalArray)

JavaScript flatMap() error: "flatMap mapper function is not callable"

I am trying to flatten an array with the following code, but when I use .flatMap() I get the error:
Uncaught TypeError: flatMap mapper function is not callable
at Array.flatMap (<anonymous>)
const data = [
{ key1: 5, key3: 2 },
{ key1: 2, key3: 1 },
{ key1: 3, key3: 2 },
{ key2: 8 },
{ key1: 5, key3: 2 },
];
var allKeys = data.map(r => Object.keys(r))
// [
// [ 'key1', 'key3' ],
// [ 'key1', 'key3' ],
// [ 'key1', 'key3' ],
// [ 'key2' ],
// [ 'key1', 'key3' ]
// ]
allKeys.flatMap();
You could use flatMap instead of map to be more concise, which eliminates the need for calling .flat() after, as it is just shorthand for .map(...).flat(). As well, you can directly pass Object.keys as the callback for flatMap, as it ignores all arguments other than the first one that it is given.
const data = [
{ key1: 5, key3: 2 },
{ key1: 2, key3: 1 },
{ key1: 3, key3: 2 },
{ key2: 8 },
{ key1: 5, key3: 2 },
];
var allKeys = data.flatMap(Object.keys)
console.log(allKeys);
In this case I should be using flat() not flatMap(). The below works as expected.
const data = [
{ key1: 5, key3: 2 },
{ key1: 2, key3: 1 },
{ key1: 3, key3: 2 },
{ key2: 8 },
{ key1: 5, key3: 2 },
];
var allKeys = data.map(r => Object.keys(r))
console.log(allKeys.flat());

I need to create a function that returns a plain javascript string that is indexed by 'name', and contains all the 'props'

My code seems to be right, but it isn't returning a ':' but a ',' at certain places of the Json result. please see desired result in the code comments.
I also don't like the "replaces" I coded to remove the array's brackets from the Json expression and I shouldn't modify the JSON string. Is there a more elegant way to do it?
// JSON Object
var items = [
{
name: "item 1",
id: 2,
props: {
a: "a prop1",
b: "b prop1",
},
values: [1, 2, 3],
},
{
name: "item 2",
id: 3,
props: {
a: "a prop2",
b: "b prop2",
},
values: [6, 1, 2, 3, 4],
},
{
name: "item 3",
id: 4,
props: {
a: "a prop3",
c: "c prop3",
},
values: [10, 1, 2, 3, 4, 5],
},
];
export function getObject(items) {
var arr = [];
for(var i in items){
arr.push(items[i].name);
arr.push(items[i].props);
}
var myJSON = JSON.stringify(arr).toString();
var test = myJSON.replace("[","{").replace("]","}"); // I couldn't find another way to extract the array data from the array brackets.
var test2 = JSON.stringify(test);
// test2 is returning: "{\"item 1\",{\"a\":\"a prop1\",\"b\":\"b prop1\"},\"item 2\",{\"a\":\"a prop2\",\"b\":\"b prop2\"},\"item 3\",{\"a\":\"a prop3\",\"c\":\"c prop3\"}}"
// but it's expected: "{\"item 1\":{\"a\":\"a prop1\",\"b\":\"b prop1\"},\"item 2\":{\"a\":\"a prop2\",\"b\":\"b prop2\"},\"item 3\":{\"a\":\"a prop3\",\"c\":\"c prop3\"}}"
return test2;
}
Use .map to transform each item into an object, which has one property, whose key is the item.name, and value is the item.props object:
const getObject = items => items.map(item => ({ [item.name]: item.props }));
// JSON Object
var items = [{
name: "item 1",
id: 2,
props: {
a: "a prop1",
b: "b prop1",
},
values: [1, 2, 3],
},
{
name: "item 2",
id: 3,
props: {
a: "a prop2",
b: "b prop2",
},
values: [6, 1, 2, 3, 4],
},
{
name: "item 3",
id: 4,
props: {
a: "a prop3",
c: "c prop3",
},
values: [10, 1, 2, 3, 4, 5],
},
];
console.log(getObject(items));
If you actually need a JSON string and not an object, then put JSON.stringify around it. (remember: There's no such thing as a "JSON Object".)
const getObject = items => JSON.stringify(items.map(item => ({ [item.name]: item.props })));
// JSON Object
var items = [{
name: "item 1",
id: 2,
props: {
a: "a prop1",
b: "b prop1",
},
values: [1, 2, 3],
},
{
name: "item 2",
id: 3,
props: {
a: "a prop2",
b: "b prop2",
},
values: [6, 1, 2, 3, 4],
},
{
name: "item 3",
id: 4,
props: {
a: "a prop3",
c: "c prop3",
},
values: [10, 1, 2, 3, 4, 5],
},
];
console.log(getObject(items));

Categories

Resources