Customizing objects in Javascript - javascript

Please help me with this customization of objects in javascript, I'm a little stuck.
Object
var stocks = [
{
"size": "2",
"count": 5,
"store": {
"id": 3,
"title": "Belconnen"
}
},
{
"size": "3",
"count": 4,
"store": {
"id": 4,
"title": "Canberra"
}
},
{
"size": "4",
"count": 4,
"store": {
"id": 5,
"title": "Bankstown"
}
},
{
"size": "5",
"count": 5,
"store": {
"id": 4,
"title": "Canberra"
}
}];
Expected Output
{3:{"sizes": {2: 3}}},
{4:{"sizes": {3: 3, 5: 3}}},
{5:{"sizes": {4: 3}}}
My code so far
for (var key in stocks) {
var stock = stocks[key];
stores[stock.store.id] = stock.store;
var store = stores[stock.store.id];
if (!store.sizes || !store.sizes.length) {
store.sizes = [stock.size];
}
}
But it keeps overiding the first size value of the store.
Thanks in advance.

This is one way to solve the problem
var stocks = [
{"size": 2, "count": 3, "store": {"id": 3, "name": "Canberra"}},
{"size": 3, "count": 3, "store": {"id": 4, "name": "Belconnen"}},
{"size": 4, "count": 3, "store": {"id": 5, "name": "Bankstown"}},
{"size": 5, "count": 3, "store": {"id": 4, "name": "Belconnen"}}];
var obj = {};
stocks.forEach(function(item){
// initialize if object key not present
if(!obj[item.store.id]){
obj[item.store.id] = {"sizes": {}};
}
obj[item.store.id]["sizes"][item.size] = item.count;
});
console.log(obj);
Here is the working fiddle https://jsfiddle.net/flyinggambit/nc3uny53/
Check the console window for fiddle output

Related

How to push a set of arrays into main array?

I want to push some arrays into the main array in single function. Here is the example :
let MainArr = [
{
"date": "2021-02-24T18:30:00.000Z",
"age": "9",
"id": 74,
"time": 4.00 },
{"date": "2021-02-24T18:30:00.000Z",
"age":"9",
"id": 74,
"time": 4.00
}];
I am getting all this data from API so next array will be like this:
let arr1 = [{
"id": 1,
"arrKey1": "schedule1"
}, {
"id": 2,
"arrKey1": "schedule2"
}]
let arr2 = [{
"id": 1,
"arrKey2": "bus1"
}, {
"id": 2,
"arrKey2": "bus2"
}]
let arr3 = [{
"id": 1,
"arrKey3": "car1"
}, {
"id": 2,
"arrKey3": "1"
}]
Now the result should reflect like this:
[{
"date": "2021-02-24T18:30:00.000Z",
"age": "9",
"id": 74,
"time": 4.00,
"arrKey1":"schedule1",
"arrKey2 ":"bus1",
"arrKey3":"car1"},
{"date ": "2021-02-24T18:30:00.000Z",
"age": "9",
"id": 74,
"time": 4.00,
"arrKey1": "schedule2",
"arrKey2": "bus2",
"arrKey3": "1"
}];
In ES6 you can use three dots. see the example:
let MainArr = [1, 2, 3];
let arr1 = [4, 5, 6];
console.log('before: ', MainArr)
MainArr.push(...arr1)
console.log('after pushing arr1: ', MainArr)

How to sort and filter out given data in React?

Given the data below:
Group the items by list id
Then sort the results first by list id then by name
Filter out the name where is blank or null.
[
{"listId": 2, "name": ""},
{"listId": 1, "name": "Item 28"},
{"listId": 1, "name": "Item 270"},
{"listId": 3, "name": null},
{"listId": 4, "name": null},
{"listId": 2, "name": "Item 23"},
{"listId": 1, "name": null},
{"listId": 2, "name": null},
{"listId": 1, "name": ""},
{"listId": 3, "name": null},
{"listId": 2, "name": null},
{"listId": 2, "name": null},
{"listId": 3, "name": "Item 68"},
{"listId": 2, "name": null},
{"listId": 4, "name": "Item 53"},
{"listId": 4, "name": ""},
{"listId": 1, "name": null},
{"listId": 2, "name": null},
]
Any help is greatly appreciated! :)
Heres a solution that might work for you:
const data = [
{"id": 755, "listId": 2, "name": ""},
{"id": 203, "listId": 2, "name": "Item 456"},
{"id": 684, "listId": 1, "name": "Item 684"},
{"id": 276, "listId": 1, "name": "Item 276"},
{"id": 736, "listId": 3, "name": null},
{"id": 926, "listId": 4, "name": null},
{"id": 808, "listId": 4, "name": "Item 808"},
{"id": 599, "listId": 1, "name": null},
{"id": 424, "listId": 2, "name": null},
{"id": 444, "listId": 1, "name": ""},
{"id": 809, "listId": 3, "name": "Item 789"},
{"id": 293, "listId": 2, "name": null},
{"id": 510, "listId": 2, "name": null},
];
function removeNull({ name }) {
return Boolean(name);
}
function sortByIdThenName(a, b) {
const n = a.listId - b.listId;
// sort by listId
if (n !== 0) {
return n;
}
// if listId is equal then sort by name
return a.name.localeCompare(b.name);
}
const sorted = data.filter(removeNull).sort(sortByIdThenName);
console.log(sorted);
Response to comments below
Sort by numeric id found in name:
function sortByIdThenIdInName(a, b) {
const n = a.listId - b.listId;
// sort by listId
if (n !== 0) {
return n;
}
// if listId is equal then sort by id in name
const [, numericIdFromNameA] = a.name.split(' ');
const [, numericIdFromNameB] = b.name.split(' ');
return parseInt(numericIdFromNameA) - parseInt(numericIdFromNameB);
}
My try.
var data = [
{ "id": 755, "listId": 2, "name": "" },
{ "id": 203, "listId": 2, "name": "" },
{ "id": 684, "listId": 1, "name": "Item 684" },
{ "id": 276, "listId": 1, "name": "Item 276" },
{ "id": 736, "listId": 3, "name": null },
{ "id": 926, "listId": 4, "name": null },
{ "id": 808, "listId": 4, "name": "Item 808" },
{ "id": 599, "listId": 1, "name": null },
{ "id": 424, "listId": 2, "name": null },
{ "id": 444, "listId": 1, "name": "" },
{ "id": 809, "listId": 3, "name": null },
{ "id": 293, "listId": 2, "name": null },
{ "id": 510, "listId": 2, "name": null },
]
var data = data.filter((d) => d.name)//clean before do anything
data.sort((a, b) => (a.name > b.name) ? 1 : ((b.name > a.name) ? -1 : 0));//https://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value
function groupBy(arr, key) {//https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects
return arr.reduce(function (rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
}
console.log(groupBy(data, "listId"));

match 2 properties' values in array of objects and filter matches based on a 3rd property's value

I've got a graph with nodes that can be connected to multiple other nodes.
Every node represents an object in an array. Within every node's object is an array that contains the ids of all the nodes linked to this node and its depth:
nodes: [
{"id":1, "depth":0, "next":[], "children":[2, 3]}, // nodes.next = [2, 3]
{"id":2, "depth":1, "next":[], "children":[1, 4, 5]}, // nodes.next = [4, 5]
{"id":3, "depth":1, "next":[], "children":[1, 6, 7]}, // nodes.next = [6, 7]
{"id":4, "depth":2, "next":[], "children":[2, 8]}, // nodes.next = [8]
{"id":5, "depth":2, "next":[], "children":[2, 9]} // nodes.next = [9]
]
I would like to traverse the graph from a certain node.
The problem is that a node's children array contains all the nodes linked to it. A node with a depth of 2 points back to a node with a depth of 1.
So I would like to create a new array within the nodes' objects, let's say nodes.next and get rid of the children that point back to a node that has a depth lower than itself.
The part that really baffles me is checking the depth of the nodes in nodes.children. I even haven't been near the part where I might check if the depth of a node in nodes.children is higher than nodes[i].depth and push nodes[i].children[i] to nodes[i].next.
If there is better way to solve this problem I'd be happy to know. My attemps have been fruitless in many ways alike:
let childDepth;
for (let i = 0; i < nodes.length; i++) {
for (let child in nodes[i].children) {
if (nodes.id === child) {
childDepth = nodes[i].depth;
}
if (childDepth > graph.nodes[i].depth) {
nodes[i].next.push(child)
}
}
}
Updated array:
const nodes = [
{ "id": 37, "depth": 0, "children": [210, 395, 265], "next": [] },
{ "id": 210, "depth": 1, "children": [37, 260, 259, 391],"next": [] },
{ "id": 256, "depth": 2, "children": [265], "next": [] },
{ "id": 259, "depth": 2, "children": [210, 397, 396], "next": [] },
{ "id": 260, "depth": 2, "children": [210], "next": [] },
{ "id": 265, "depth": 1, "children": [37, 256, 388, 394, 271, 269], "next": [] },
{ "id": 269, "depth": 2, "children": [265], "next": [] },
{ "id": 271, "depth": 2, "children": [265], "next": [] },
{ "id": 388, "depth": 2, "children": [265], "next": [] },
{ "id": 391, "depth": 2, "children": [210], "next": [] },
{ "id": 394, "depth": 2, "children": [265], "next": [] },
{ "id": 395, "depth": 1, "children": [37], "next": [] },
{ "id": 396, "depth": 3, "children": [259, 413], "next": [] },
{ "id": 397, "depth": 3, "children": [259], "next": [] },
{ "id": 413, "depth": 4, "children": [396], "next": [] }
];
Kindly take a look on the below code to see if it's what you're looking for
const array = [
{id:1, depth:0, next:[], children:[2, 3]},
{id:2, depth:1, next:[], children:[1, 4, 5]},
{id:3, depth:1, next:[], children:[1, 6, 7]},
{id:4, depth:2, next:[], children:[2, 8]},
{id:5, depth:2, next:[], children:[2, 9]}
]
array.forEach(x => {
let { children, depth } = x;
for(let i=depth; i< children.length; i++){
x.next.push(children[i]);
}
});
Output as below:
[
{"id":1,"depth":0,"next":[2,3],"children":[2,3]},
{"id":2,"depth":1,"next":[4,5],"children":[1,4,5]},
{"id":3,"depth":1,"next":[6,7],"children":[1,6,7]},
{"id":4,"depth":2,"next":[],"children":[2,8]},
{"id":5,"depth":2,"next":[],"children":[2,9]}
]

How to join two objects

I will like to know how to joins the parents.json with the childrens.json using JavaScript. I need to get the result.json
First object: parents.json
{
"name": "ParentsLevel2",
"Level": 1,
"children": [
{
"name": "analytics",
"level": 2,
},
{
"name": "animate",
"level": 2
}
]
}
Second object: childrens.json
{
"name": "childrensLevel3",
"Level": 1,
"children": [
{
"name": "analytics1",
"level": 3,
"parent": "analytics"
},
{
"name": "analytics2",
"level": 3,
"parent": "analytics"
},
{
"name": "animate1",
"level": 3,
"parent": "animate"
},
{
"name": "animate2",
"level": 3,
"parent": "animate"
}
]
The result: result.json
{
"name": "Root",
"Level": 1,
"children": [
{
"name": "analytics",
"level": 2,
"children": [
{
"name": "analytics1",
"level": 3
},
{
"name": "analytics2",
"level": 3
}
]
},
{
"name": "animate",
"level": 2
"children": [
{
"name": "animate1",
"level": 3
}
]
}
]
}
I have this:
var parent= parents.json
var child= childrens.json
var obj=parent["children"];
var obj2=child["children"];
for(i in obj){
for(c in obj2){
if(obj[i].name == obj2[c].parent){
//here is the push of the child associated to the parent, but how and
//also how create the result.json I need to create other object to put all together.
}
}
}
try this code
var obj1 = { "name": "ParentsLevel2", "Level": 1, "children": [ { "name": "analytics", "level": 2, }, { "name": "animate", "level": 2 } ]
};
var obj2 = { "name": "childrensLevel3", "Level": 1, "children": [ { "name": "analytics1", "level": 3, "parent": "analytics" }, { "name": "analytics2", "level": 3, "parent": "analytics" }, { "name": "animate1", "level": 3, "parent": "animate" }, { "name": "animate2", "level": 3, "parent": "animate" } ]};
var obj = {};
obj [0] = obj 1;
obj [1] = obj 2;
console.log(obj);
Solution:
var parentJson={
"name": "ParentsLevel2",
"Level": 1,
"children": [
{
"name": "analytics",
"level": 2,
"children":[]
},
{
"name": "animate",
"level": 2,
"children":[]
}
]
};
var sonJson={
"name": "ChildrenLevel3",
"Level": 1,
"children": [
{
"name": "analytics1",
"level": 3,
"parent": "analytics"
},
{
"name": "analytics2",
"level": 3,
"parent": "analytics"
}
]
};
//push a new object to the parentJson
//parentJson["children"].push("object to push");
//push a new object to the sonJson
//sonJson["children"].push("object to push");
//join
var objSon=sonJson["children"];
var oP=parentJson["children"];
for(p in oP){
for(s in objSon){
if(oP[p].name==objSon[s].parent){
alert("match");
oP[p].children.push(objSon[s]);
}
}
}
//create the result
var result=[];
var obj=oP;
for(i in obj){
var temp=[];
temp.push("FirstName");
temp.push(obj[i].name);
temp.push("Level");
temp.push(obj[i].level);
temp.push("Hijos")
temp.push(obj[i].children);
result.push(temp);
$("#D3").html(JSON.stringify(result));
$("#D3").prepend("result=")
jsfiddle Solution

iterate over heavily nested javascript object to find data

I have below JavaScript object pattern.
{
"_id": 2,
"children": [
{
"_id": 3,
"children": [
{
"_id": 5,
"children": [
{
"_id": 9,
"children": [],
"id_category": 9,
"parent_id": 5
},
{
"_id": 10,
"children": [],
"id_category": 10,
"parent_id": 5
}],
"id_category": 5,
"parent_id": 3
},
{
"_id": 6,
"children": [],
"id_category": 6,
"parent_id": 3
}],
"id_category": 3,
"parent_id": 2
},
{
"_id": 4,
"children": [
{
"_id": 7,
"children": [],
"id_category": 7,
"parent_id": 4
},
{
"_id": 8,
"children": [],
"id_category": 8,
"parent_id": 4
}],
"id_category": 4,
"parent_id": 2
}],
"id_category": 2,
"parent_id": 1
}
Now I want to get whole data for which I pass the value of _id.
For example if I pass 5, it will return the whole object of 5
{
"_id": 5,
"children": [
{
"_id": 9,
"children": [],
"id_category": 9,
"parent_id": 5
},
{
"_id": 10,
"children": [],
"id_category": 10,
"parent_id": 5
}],
"id_category": 5,
"parent_id": 3
}
The problem is Level of nesting is unlimited .
Please suggest.
Use a recursive function.
Something like this (untested, but should be ok)
function search(value, tree) {
if (tree._id === value)
return value;
var numChildren = tree.children.length;
for (var i = 0; i < numChildren; ++i) {
var result = search(value, tree.children[i]);
if (result)
return result;
}
return null;
}
var tree = {...your big json hash...};
var found = search(5, tree);
console.log(found);

Categories