Filter and get data from JSON - javascript

How to get the data value from the list, the size of the array, the main thing is not through the index, because the order of the arrays can change and I can get specific data from the code === "size". Unfortunately, the structure cannot be changed. It came to mind only through the filter, by index, but it is impossible
The result should be 100 150
https://jsoneditoronline.org/#left=cloud.b10638604c214b189f87747414e06035
[
[
"color",
{
"name": "Цвет",
"code": "color",
"list": [
{
"value": "Зеленый"
},
{
"value": "Красный"
}
]
}
],
[
"size",
{
"name": "Размер",
"code": "size",
"list": [
{
"value": "100"
},
{
"value": "150"
}
]
}
]
]

This data structure is terrible, but a quick fix could be something like this
const data = [
[
"color",
{
"name": "Цвет",
"code": "color",
"list": [
{
"value": "Зеленый"
},
{
"value": "Красный"
}
]
}
],
[
"size",
{
"name": "Размер",
"code": "size",
"list": [
{
"value": "100"
},
{
"value": "150"
}
]
}
]
]
const size = data.filter(element => element[1].code === 'size')[0][1].list.map(element => element.value)
console.log(size)

Related

nest items in JSON based on value?

Trying to get my head around this one..
Incoming data looks like:
[
{
"value": {
"label": "MZ Algal bloom",
"type": "case",
"incident": {
"name": "Algal bloom"
},
"personName": "Lionel Carter"
}
},
{
"value": {
"label": "BW Algal bloom",
"type": "case",
"incident": {
"name": "Algal bloom"
},
"personName": "Jerome Yost"
}
},
{
"value": {
"label": "Detergent",
"type": "case",
"incident": null,
"personName": "Jerald Legros"
}
}
]
I would like to transform this into
[
{
"label": "Algal bloom",
"children": [
{ "label": "Lionel Carter", "type": "case"},
{ "label": "Jerome Yost", "type": "case" }]
},
{ "label": "Detergent", "type": "case" }
]
Basically, the rule is that if incident is not NULL then the incident name becomes the parent and the children hold the personName - otherwise we simply pass through the label and type. I can walk the array and switch out the label with the incident name, but I'm not sure how to group up the incidents..
It's basic grouping with an exception for elements without incident.
You can group the elements without incident in a separate group:
const data = [{"value": {"label": "MZ Algal bloom","type": "case","incident": {"name": "Algal bloom"},"personName": "Lionel Carter"}},{"value": {"label": "BW Algal bloom","type": "case","incident": {"name": "Algal bloom"},"personName": "Jerome Yost"}},{"value": {"label": "Detergent","type": "case","incident": null,"personName": "Jerald Legros"}}];
function group(data) {
const result = data.reduce((acc, { value }) => {
if (!value.incident) {
acc.ungrouped.push({ label: value.label, type: value.type });
} else {
if (!acc.groups[value.incident.name]) acc.groups[value.incident.name] = { label: value.incident.name, children: [] };
acc.groups[value.incident.name].children.push({ label: value.personName, type: value.type });
}
return acc;
}, { groups: {}, ungrouped: [] });
return [...Object.values(result.groups), ...result.ungrouped];
}
console.log(group(data));

javascript print nested array to screen

I have a data array, there are multiple objects in this array, and the data object is an array. There may be more than one object in this array. How can I copy these objects under a single array?
const test = []
const data = [
{
"_id": "124141",
"name": "test",
"data": [
{
"price":10,
"title": "sda"
},
]
},
{
"_id": "2525",
"name": "test2",
"data": [
{
"price":20,
"title": "asdas"
},
]
}
]
[{
"price":10,
"title": "sda"
},
{
"price":20,
"title": "asdas"
},
]
If this is the output I expect, it should be like this. how can I do that
const data = [
{
"_id": "124141",
"name": "test",
"data": [
{
"price":10,
"title": "sda"
},
{
"price":99,
"title":"aaaaa"
}
]
},
{
"_id": "2525",
"name": "test2",
"data": [
{
"price":20,
"title": "asdas"
},
]
}
];
console.log(data.map(e => e.data).flat());
// OR
console.log(data.flatMap(e => e.data));

Replace all object properties with a new name

I want to replace all object properties label to the property name text.
Given:
[
{
"value": "45a8",
"label": "45A8",
"children": [
{
"value": "45a8.ba08",
"label": "BA08",
"children": [
{
"value": "45a8.ba08.45a8",
"label": "45A8"
}
],
"checked": false
}
]
},
...
]
Needed:
[
{
"value": "45a8",
"text": "45A8",
"children": [
{
"value": "45a8.ba08",
"text": "BA08",
"children": [
{
"value": "45a8.ba08.45a8",
"text": "45A8"
}
],
"checked": false
}
]
},
...
]
You can first stringify the the data with JSON.stringify() then replace the string. Finally parse the string with JSON.parse():
var data = [
{
"value": "45a8",
"label": "45A8",
"children": [
{
"value": "45a8.ba08",
"label": "BA08",
"children": [
{
"value": "45a8.ba08.45a8",
"label": "45A8"
}
],
"checked": false
}
]
}
];
data = JSON.parse(JSON.stringify(data).replaceAll('"label"', '"text"'));
console.log(data);
Update: You can try using RegEx like the following way:
var data = [
{
"value": "45a8",
"label": "45A8",
"children": [
{
"value": "45a8.ba08",
"label": "BA08",
"children": [
{
"value": "45a8.ba08.45a8",
"label": "45A8"
}
],
"checked": false
}
]
}
];
var find = '"label"';
var re = new RegExp(find, 'g');
data = JSON.parse(JSON.stringify(data).replace(re, '"text"'));
console.log(data);
You can also browse through the keys and find the label key. Get it's value assign it to the new key i.e. text and delete the old key i.e. label.
let data = [
{
"value": "45a8",
"label": "45A8",
"children": [
{
"value": "45a8.ba08",
"label": "BA08",
"children": [
{
"value": "45a8.ba08.45a8",
"label": "45A8"
}
],
"checked": false
}
]
}
]
for (const key in data.keys()){
if(key === "label"){
data.text = data[key]
delete data.key
}
}
You can also do this with using recursion. It could be something like this:
const nestArr=[ { "value": "45a8", "label": "45A8", "children": [ { "value": "45a8.ba08", "label": "BA08", "children": [ { "value": "45a8.ba08.45a8", "label": "45A8" } ], "checked": false } ] }];
changeLabelToText=arr=>{
return arr.map(({label,...rest})=>{
if(rest.children) rest.children = changeLabelToText(rest.children);
return {text:label, ...rest}
})
};
console.log(changeLabelToText(nestArr));

How to check if an array contains two values with Javascript

I have a JSON object that has an array as below
{
"objects": [
{
"severity": "LOW",
"tags": [
{
"key": "account",
"values": [
"account2"
]
},
{
"key": "accountId",
"values": [
"2"
]
}
],
"name": "object1"
},
{
"severity": "HIGH",
"tags": [
{
"key": "account",
"values": [
"account2"
]
},
{
"key": "accountId",
"values": [
"2"
]
}
],
"name": "object2"
},
{
"severity": "MEDIUM",
"tags": [
{
"key": "account",
"values": [
"account44"
]
},
{
"key": "accountId",
"values": [
"44"
]
}
],
"name": "object2"
},
{
"severity": "HIGH",
"tags": [
{
"key": "account",
"values": [
"account42"
]
},
{
"key": "accountId",
"values": [
"42"
]
}
],
"name": "object2"
}
]
}
I want to be able to go through the array using javascript and if severity is HIGH and acccountID matches 2 for example to set a warning. Even though account 2 might have a severity of LOW as shown, I still want to make the if condition true.
So something like if (objects.some(a =>(a.severity ==="LOW" && ...... or whatever better option there is.
You can loop through your object and match your properties like this
const data = { "objects": [ { "severity": "LOW", "tags": [ { "key": "account", "values": [ "account2" ] }, { "key": "accountId", "values": [ "2" ] } ], "name": "object1" }, { "severity": "HIGH", "tags": [ { "key": "account", "values": [ "account2" ] }, { "key": "accountId", "values": [ "2" ] } ], "name": "object2" }, { "severity": "MEDIUM", "tags": [ { "key": "account", "values": [ "account44" ] }, { "key": "accountId", "values": [ "44" ] } ], "name": "object2" }, { "severity": "HIGH", "tags": [ { "key": "account", "values": [ "account42" ] }, { "key": "accountId", "values": [ "42" ] } ], "name": "object2" } ] };
// Loop
for(let i = 0; i < data.objects.length; i++) {
// Set severity
const severity = data.objects[i].severity;
// Set ID
let id; for(let ii = 0; ii < data.objects[i].tags.length; ii++) if(data.objects[i].tags[ii].key === 'accountId') id = data.objects[i].tags[ii].values[0];
// Do logic here
if(severity === 'LOW' && id === '2') console.log(data.objects[i]);
}
If you're loop-avert:
if (objects.some(e => e.severity === severity || e.tags.some(t => t.key === 'accountId' && t.values.includes(accountId)))) {
...
For clarity, that closure is:
return e =>
e.severity === severity ||
e.tags.some(t =>
t.key === 'accountId' &&
t.values.includes(accountId));
e.g.
const j = { "objects": [ { "severity": "LOW", "tags": [ { "key": "account", "values": [ "account2" ] }, { "key": "accountId", "values": [ "2" ] } ], "name": "object1" }, { "severity": "HIGH", "tags": [ { "key": "account", "values": [ "account2" ] }, { "key": "accountId", "values": [ "2" ] } ], "name": "object2" }, { "severity": "MEDIUM", "tags": [ { "key": "account", "values": [ "account44" ] }, { "key": "accountId", "values": [ "44" ] } ], "name": "object2" }, { "severity": "HIGH", "tags": [ { "key": "account", "values": [ "account42" ] }, { "key": "accountId", "values": [ "42" ] } ], "name": "object2" } ] };
function condition(severity, accountId) {
return e =>
e.severity === severity ||
e.tags.some(t =>
t.key === 'accountId' &&
t.values.includes(accountId));
}
if (j.objects.some(condition('LOW', '2'))) {
console.log("warning: low || 2");
}
if (j.objects.some(condition('SUPER_HIGH', '4048'))) {
console.log("warning: super high || 4048");
}

JS How to remove an object from array in a forEach loop?

I have a data object with following contents:
{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}
I want to remove block that has key yellow, by looping over blocks, rest of the data should be preserved as is. So expected end result would be
{
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
}
Data is dynamic so I dont know what would be returned, it might have a match for my condition or it might not.
I've tried a bunch of approaches but nothing seems to have worked so far. I can use lodash too if its any easier. None of those seems to be working. Any help/direction is appreciated
1. Using **delete**
const deleteUnwantedBlock = contentObj => {
const updatedData = contentObj;
const blocks = _.get(updatedData, 'blocks', []);
blocks.forEach(block => {
if (block.key.includes('yellow')) {
delete updatedData.block;
}
});
return updatedData;
};
console.log(deleteUnwantedBlock(data.content));```
2. Using rest operator:
const deleteUnwantedBlock = contentObj => {
const blocks = _.get(contentObj, 'blocks', []);
blocks.forEach(block => {
if (block.key.includes('yellow')) {
let { block, ...restOfTheData } = updatedData;
}
return { ...updatedEntry };
});
};
console.log(deleteUnwantedBlock(data.content));
You just need to filter:
const obj = {
"content": {
"id": "someID",
"type": "unit",
"method": "xyz",
"blocks": [{
"key": "blue",
"data": [
"Array"
]
}, {
"key": "red",
"data": [
"Array"
]
}, {
"key": "yellow",
"data": [
"Array"
]
}, {
"key": "black",
"data": [
"Array"
]
}],
"notes": "abc"
}
};
obj.content.blocks = obj.content.blocks.filter(({ key }) => key !== 'yellow');
console.log(obj);

Categories

Resources