There can two sets of objects
First can be a straight forward where is no children
const noChildObj = [{
"id": 1,
"label": ["Description"],
"lines": 1,
"type": "string",
"precision": 2,
"width": 167.8
}, {
"id": 2,
"label": ["Information", "Ratio"],
"lines": 2,
"type": "number",
"precision": 2,
"width": 167.8
}, {
"id": 3,
"label": ["Tracking", "Error"],
"lines": 2,
"type": "number",
"precision": 2,
"width": 167.8
}]
So,in this case, there is no child , so property 'width' is at the topmost layer.
Second is where nesting of objects occur
So each object in the array will have a child object
[{
"id": "257",
"label": [""],
"lines": 1,
"children": [{
"id": "Description",
"label": ["Dates"],
"lines": 1,
"type": "date",
"precision": null,
"width": 839
}]
}, {
"id": "258",
"label": ["Cumulative Return"],
"lines": 1,
"children": [{
"id": 12,
"label": ["Russell 1000 Value - Price Return"],
"lines": 1,
"type": "number",
"precision": 2,
"width": 839
}]
}]
Here each object has a child object where the property width exists
This nesting is not limited to just 1 level
It can go upto 4 levels
So my use case requires if the innermost child has width undefined or not
I do realise that through recursion , we can traverse and find out..
But is there any function which can do it in less lines of code..may be in lodash
Please help
Know only how to do with recursion:
const objArray = [{
"id": 1,
"label": ["Description"],
"lines": 1,
"type": "string",
"precision": 2,
"width": 167.8
}, {
"id": "257",
"label": [""],
"lines": 1,
"children": [{
"id": "Description",
"label": ["Dates"],
"lines": 1,
"type": "date",
"precision": null,
"width": 839
}]
}]
const getWidthDeep = (el) => el.children && el.children[0]
? getWidthDeep(el.children[0])
: el.width
const result = objArray.map(getWidthDeep)
console.log(result)
Related
I have two arrays, Array 1 containing the sections, and Array 2 containing the objects, the goal is to insert the objects from Array 2 inside the objects into Array1 depending on the type (Sides or Sauces), for example: Each object from Array 2 containing the element type:Sauces should be set in an array inside the object of Array 1 with type:Sauces and so on. I tried by using the forEach function but since I'm relatively new to JavaScript I don't know how to proceed
Array 1 (Sections)
Array [
Object {
"required": false,
"type": "Sides",
},
Object {
"required": true,
"type": "Sauces",
},
]
Array 2 (List of Objects)
Array [
Object {
"id": 2.01,
"price": "1",
"title": "Hot Sauce",
"type": "Sauces",
},
Object {
"id": 2.02,
"price": 1,
"title": "Medium Sauce",
"type": "Sauces",
},
Object {
"id": 1.01,
"price": 1,
"title": "Ranch",
"type": "Sides",
},
Object {
"id": 1.02,
"price": 1,
"title": "Blue Cheese",
"type": "Sides",
},
]
this is what I'm trying to achieve:
Array [
Object {
"required": false,
"type": "Sides",
"data": [
Object {
"id": 1.01,
"price": 1,
"title": "Ranch",
"type": "Sides",
},
Object {
"id": 1.02,
"price": 1,
"title": "Blue Cheese",
"type": "Sides",
},
]
},
Object {
"required": true,
"type": "Sauces",
"data":[
Object {
"id": 2.01,
"price": "1",
"title": "Hot Sauce",
"type": "Sauces",
},
Object {
"id": 2.02,
"price": 1,
"title": "Medium Sauce",
"type": "Sauces",
},
]
},
]
this should work for you:
arr1.forEach((a,i) => {
a["data"] = arr2.filter(b => b.type == a.type);
})
I name Array1 = categories
I name Array2 = elements
You need to map on each.
const test = categories.map((cat) => {
elements.map((el) => {
if (el.type === cat.type) {
cat.elements.push(el);
}
return el;
});
return cat;
});
console.log(test);
I need to convert below unformatted JSON format into formatted input. We need to find id's similar to parent id for different items inside array element of object and then need to push it into children to that id. Below is my code that needs to transform
Input
{
"0": [
{
"id": 10,
"title": "House",
"level": 0,
"children": [],
"parent_id": null
}
],
"1": [
{
"id": 12,
"title": "Red Roof",
"level": 1,
"children": [],
"parent_id": 10
},
{
"id": 18,
"title": "Blue Roof",
"level": 1,
"children": [],
"parent_id": 10
}
],
"2": [
{
"id": 17,
"title": "Blue Windoww",
"level": 2,
"children": [],
"parent_id": 12
},
{
"id": 16,
"title": "Door",
"level": 2,
"children": [],
"parent_id": 13
}
]
}
Output
[
{
"id": 10,
"title": "House",
"level": 0,
"children": [
{
"id": 12,
"title": "RedRoofff",
"level": 1,
"children": [
{
"id": 17,
"title": "Blue Windoww",
"level": 2,
"children": [],
"parent_id": 12
}
],
"parent_id": 10
},
{
"id": 18,
"title": "Blue Roof",
"level": 1,
"children": [],
"parent_id": 10
},
{
"id": 13,
"title": "Wall",
"level": 1,
"children": [
{
"id": 16,
"title": "Door",
"level": 2,
"children": [],
"parent_id": 13
}
],
"parent_id": 10
}
],
"parent_id": null
}
]
Please find the solution to above problem.
first, we track the node with Id and then we update the children array like this.
(btw, your input have a missing node, 13)
const input = {
"0": [{
"id": 10,
"title": "House",
"level": 0,
"children": [],
"parent_id": null
}, {
"id": 13,
"title": "Wall",
"level": 0,
"children": [],
"parent_id": null
}],
"1": [{
"id": 12,
"title": "Red Roof",
"level": 1,
"children": [],
"parent_id": 10
},
{
"id": 18,
"title": "Blue Roof",
"level": 1,
"children": [],
"parent_id": 10
},
],
"2": [{
"id": 17,
"title": "Blue Windoww",
"level": 2,
"children": [],
"parent_id": 12
},
{
"id": 16,
"title": "Door",
"level": 2,
"children": [],
"parent_id": 13
},
]
};
const results = [];
const mapId2Node = Object.values(input).reduce((acc, vals) => {
vals.forEach(val => {
acc[val.id] = val;
if (val.parent_id === null) {
results.push(val);
}
});
return acc;
}, {});
Object.values(input).forEach(vals => {
vals.forEach(val => {
if (val.parent_id !== null) {
mapId2Node[val.parent_id].children.push(val);
}
});
});
conosle.log(results);
I am trying to get specific object from a whole object below is the example
by using localStorage.getItem('shop/elasticCache/shirt');
I get below data
{"description":"Tech Shirt","configurable_options":[{"attribute_id":80,"values":[{"value_index":"5176","label":"RUST"}],"label":"Color","attribute_code":"color"},{"attribute_id":125,"values":[{"value_index":"2898","label":"Small"},{"value_index":"2901","label":"Medium"},{"value_index":"2904","label":"Large"}],"label":"Size","attribute_code":"size"}],"tsk":1594790209,"size_options":[2898,2901,2904],"regular_price":28,"final_price":null,"price":28,"color_options":[5176],"special_from_date":null,"id":250659,"category":[{"category_id":2,"name":"Default Category","position":1},{"category_id":3,"name":"Clothing","position":14985},{"category_id":30,"name":"Bottoms","position":798},{"category_id":58,"name":"Leggings","position":1},{"category_id":1130,"name":"Char Test Category","position":30}],"sku":"S155551","product_links":[{"link_type":"related","linked_product_sku":null,"linked_product_type":null,"position":0,"sku":"P100031"},{"link_type":"related","linked_product_sku":null,"linked_product_type":null,"position":0,"sku":"P100031"}
I am trying to get
{"category_id":3,"name":"Clothing","position":14985},{"category_id":30,"name":"Bottoms","position":798},{"category_id":58,"name":"Leggings","position":1},{"category_id":1130,"name":"Char Test Category","position":30}]
Is their any way it can be done ?
const {category} = JSON.parse(localStorage.getItem('shop/elasticCache/shirt');)
or
const {category } = {
"description": "Tech Shirt",
"configurable_options": [{
"attribute_id": 80,
"values": [{
"value_index": "5176",
"label": "RUST"
}],
"label": "Color",
"attribute_code": "color"
}, {
"attribute_id": 125,
"values": [{
"value_index": "2898",
"label": "Small"
}, {
"value_index": "2901",
"label": "Medium"
}, {
"value_index": "2904",
"label": "Large"
}],
"label": "Size",
"attribute_code": "size"
}],
"tsk": 1594790209,
"size_options": [2898, 2901, 2904],
"regular_price": 28,
"final_price": null,
"price": 28,
"color_options": [5176],
"special_from_date": null,
"id": 250659,
"category": [{
"category_id": 2,
"name": "Default Category",
"position": 1
}, {
"category_id": 3,
"name": "Clothing",
"position": 14985
}, {
"category_id": 30,
"name": "Bottoms",
"position": 798
}, {
"category_id": 58,
"name": "Leggings",
"position": 1
}, {
"category_id": 1130,
"name": "Char Test Category",
"position": 30
}],
"sku": "S155551",
"product_links": [{
"link_type": "related",
"linked_product_sku": null,
"linked_product_type": null,
"position": 0,
"sku": "P100031"
}, {
"link_type": "related",
"linked_product_sku": null,
"linked_product_type": null,
"position": 0,
"sku": "P100031"
}]
}
objc={"description":"Tech Shirt","configurable_options":
[{"attribute_id":80,"values":[{"value_index":"5176","label":"RUST"}],
"label":"Color","attribute_code":"color"},
{"attribute_id":125,"values":[{"value_index":"2898","label":"Small"}
,{"value_index":"2901","label":"Medium"},
{"value_index":"2904","label":"Large"}],
"label":"Size","attribute_code":"size"}],
"tsk":1594790209,"size_options":[2898,2901,2904]
,"regular_price":28,"final_price":null,"price":28,
"color_options":[5176],"special_from_date":null,"id":250659,
"category":[{"category_id":2,"name":"Default Category","position":1},
{"category_id":3,"name":"Clothing","position":14985},
{"category_id":30,"name":"Bottoms","position":798},
{"category_id":58,"name":"Leggings","position":1},
{"category_id":1130,"name":"Char Test Category","position":30}],
"sku":"S155551","product_links":
[{"link_type":"related","linked_product_sku":null,"linked_product_type":null,"position":0,"sku":"P100031"},
{"link_type":"related","linked_product_sku":null,"linked_product_type":null,"position":0,"sku":"P100031"}]
}
res = objc["category"]
res.shift()
console.log(res)
$(document).ready(function () {
var jsonObj = {
"description": "Tech Shirt",
"configurable_options": [{
"attribute_id": 80,
"values": [{
"value_index": "5176",
"label": "RUST"
}],
"label": "Color",
"attribute_code": "color"
}, {
"attribute_id": 125,
"values": [{
"value_index": "2898",
"label": "Small"
}, {
"value_index": "2901",
"label": "Medium"
}, {
"value_index": "2904",
"label": "Large"
}],
"label": "Size",
"attribute_code": "size"
}],
"tsk": 1594790209,
"size_options": [2898, 2901, 2904],
"regular_price": 28,
"final_price": null,
"price": 28,
"color_options": [5176],
"special_from_date": null,
"id": 250659,
"category": [{
"category_id": 2,
"name": "Default Category",
"position": 1
}, {
"category_id": 3,
"name": "Clothing",
"position": 14985
}, {
"category_id": 30,
"name": "Bottoms",
"position": 798
}, {
"category_id": 58,
"name": "Leggings",
"position": 1
}, {
"category_id": 1130,
"name": "Char Test Category",
"position": 30
}],
"sku": "S155551",
"product_links": [{
"link_type": "related",
"linked_product_sku": null,
"linked_product_type": null,
"position": 0,
"sku": "P100031"
}, {
"link_type": "related",
"linked_product_sku": null,
"linked_product_type": null,
"position": 0,
"sku": "P100031"
}]
};
for(var i = 1; i < jsonObj.category.length; i++){
console.log(jsonObj.category[i]);
}
});
You can iterate through the entire object and can get the required values. The above code gives the values of category from index 1.
I've a nested object.
Now, I need to check if the object contains 'items' as a key anywhere which is an 'array' always, then replace 'type' : 'list' by 'type': 'array' of the parent.
It works well for the 1st level but when it comes to the nested object which contains 'items' again, I'm stuck.
function convertData() {
const arr = {
"type": "list",
"items": [{
"type": "list",
"items": [{
"type": "string",
"value": 0,
"unit": "",
"pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$"
}, {
"type": "string",
"value": 0.1875,
"unit": "rem",
"pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$"
}, {
"type": "string",
"value": 0.75,
"unit": "rem",
"pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$"
}, {
"type": "string",
"value": 0,
"unit": "",
"pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$"
}]
}, {
"type": "string",
"value": {
"r": 161,
"g": 161,
"b": 161,
"a": 0.75,
"hex": "#a1a1a1"
},
"pattern": "^rgba?\\(((25[0-5]|2[0-4]\\d|1\\d{1,2}|\\d\\d?)\\s*,\\s*?){2}(25[0-5]|2[0-4]\\d|1\\d{1,2}|\\d\\d?)\\s*,?\\s*([01]\\.?\\d*?)?\\)"
}]
};
if (Array.isArray(arr.items)) {
arr.type = "array";
console.log(arr);
}
}
<button onclick="convertData()">Click me!</button>
You can do that using recursion.
Create a function changeValue which takes an object as argument.
Check the object has key items using Object.hasOwnProperty()
If it contains change the type to "array" and call the function recursively on its each item.
function convertData() {
const arr = { "type": "list", "items": [{ "type": "list", "items": [{ "type": "string", "value": 0, "unit": "", "pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$" }, { "type": "string", "value": 0.1875, "unit": "rem", "pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$" }, { "type": "string", "value": 0.75, "unit": "rem", "pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$" }, { "type": "string", "value": 0, "unit": "", "pattern": "^(auto|0)$|^[+-]?[0-9]+(\\.)?([0-9]+)?(rem|px|em|ex|%|in|cm|mm|pt|pc)$" }] }, { "type": "string", "value": { "r": 161, "g": 161, "b": 161, "a": 0.75, "hex": "#a1a1a1" }, "pattern": "^rgba?\\(((25[0-5]|2[0-4]\\d|1\\d{1,2}|\\d\\d?)\\s*,\\s*?){2}(25[0-5]|2[0-4]\\d|1\\d{1,2}|\\d\\d?)\\s*,?\\s*([01]\\.?\\d*?)?\\)" }] };
changeValue(arr);
console.log(arr)
}
function changeValue(obj){
if(obj.hasOwnProperty('items')){
obj.type = "array";
obj.items.forEach(x => changeValue(x))
}
}
<button onclick="convertData()">Click me!</button>
Suppose I have the following json file and I would like to return the 'existing.primaryBundle.products' array preferrably with lodash:
{
"existing": {
"hasPlatinum": false,
"primaryBundle": {
"id": "2008",
"name": "TV - Entertainment, Sport",
"products": [
{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
},
{
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false,
"swappableProducts": [
{
"name": "Movies",
"id": "105",
"price": 2000,
"gifted": false
}
]
}
]
},
"extrasBundle": {
"id": "131",
"name": "Optional Extras - MUTV (Sports), LFCTV (Sports), Chelsea TV (Sports)",
"products": [
{
"name": "MUTV (Sports)",
"id": "665",
"price": 0,
"gifted": false
},
{
"name": "LFCTV (Sports)",
"id": "666",
"price": 0,
"gifted": false
},
{
"name": "Chelsea TV (Sports)",
"id": "667",
"price": 0,
"gifted": false
}
]
}
}
}
I have tried lodash and use this statement:
list2 = _.pick(existing,'primaryBundle.products')
But this returns an error and not the wanted result. How can I select this products array?
you could use _.get(nameOfObject, 'existing.primaryBundle.products') of course you would need to name your object like I've done below with sampleObject;
check out the lodash docs too
const sampleObject = {
"existing": {
"hasPlatinum": false,
"primaryBundle": {
"id": "2008",
"name": "TV - Entertainment, Sport",
"products": [{
"name": "Entertainment",
"id": "100",
"price": 2600,
"gifted": false
}, {
"name": "Sport",
"id": "107",
"price": 2500,
"gifted": false,
"swappableProducts": [{
"name": "Movies",
"id": "105",
"price": 2000,
"gifted": false
}]
}]
},
"extrasBundle": {
"id": "131",
"name": "Optional Extras - MUTV (Sports), LFCTV (Sports), Chelsea TV (Sports)",
"products": [{
"name": "MUTV (Sports)",
"id": "665",
"price": 0,
"gifted": false
}, {
"name": "LFCTV (Sports)",
"id": "666",
"price": 0,
"gifted": false
}, {
"name": "Chelsea TV (Sports)",
"id": "667",
"price": 0,
"gifted": false
}]
}
}
}
console.log(_.get(sampleObject, 'existing.primaryBundle.products'));
The main reason why it returns an error is because existing is not a global scoped object, you have to assign object to some variable like const obj = {...} and then pass the parameter to _pick method as obj.existing, yet I don't see a reason to use lodash in here, you can just reference the path to that object directly.