Filtration of multilevel JSON array - javascript

I am trying to duplicate value only one time as well as unique from my JSON array.
I have tried the following code.
return_data = {};
return_data.planner = [{
"date": "2019-08-30T12:10:08.000Z",
"event": [{
"name": "Event 1",
"color": "#ccccc"
}]
},
{
"date": "2019-09-30T10:10:08.000Z",
"event": [{
"name": "Event 5",
"color": "#ccccc"
},
{
"name": "Event 4",
"color": "#ccccc"
},
{
"name": "Event 3",
"color": "#ccccc"
}
]
},
{
"date": "2019-09-30T10:10:08.000Z",
"event": [{
"name": "Event 5",
"color": "#ccccc"
},
{
"name": "Event 4",
"color": "#ccccc"
},
{
"name": "Event 3",
"color": "#ccccc"
}
]
},
{
"date": "2019-09-30T10:10:08.000Z",
"event": [{
"name": "Event 5",
"color": "#ccccc"
},
{
"name": "Event 4",
"color": "#ccccc"
},
{
"name": "Event 3",
"color": "#ccccc"
}
]
}
];
res.header('Content-Type', 'application/json');
res.send(JSON.stringify(return_data));
Using above json array:
var u_array = [];
var tem = JSON.parse(JSON.stringify(return_data.response.planner));
for (var i = 0; i < tem.length; i++) {
console.log(tem[i].date);
var status = true;
for (var j = 0; j < u_array.length; j++) {
if (u_array[j].date == tem[i].date) {
status = false;
break;
}
}
if (status) {
u_array.push(tem[i]);
}
};
return_data.response.planner = u_array;
I expect the duplicate value only one time with unique values.

There are many different ways to do what you need. You can follow this thread for some pointers.
Here's one way to get distinct-
/**
* inputArray = Input array
* keySelector = A function to select which key should be used to determine if element is distinct
* keepFirstMatch =
* true - If there is a matching element, and you want to keep the first original item
* false - If there is a matching element and you want to override the original item so that it gets overwritten by latest value in the array
*/
function getDistinct(inputArray, keySelector, keepFirstMatch = false) {
const result = inputArray.reduce((acc, curr) => {
if (keepFirstMatch) {
if (typeof (acc[keySelector(curr)]) === 'undefined') {
acc[keySelector(curr)] = curr;
}
} else {
acc[keySelector(curr)] = curr;
}
return acc;
}, {});
return Object.keys(result).map(k => result[k]);
}
let distinct = getDistinct(planner, (c) => c.date);

Related

Empty array when filter inside deep an object

I made this function to filter in deep an array of object, but at the end the result is empty. If i check with console.log inside the if statement , it show me filtered object, but resultPost return me empty value. I also tryed to push inside an empty array the filtered value, but not work.
const post = [{
"name": "new post",
"description": "simple desc",
"taxonomies": {
"categories": {
"0": {
"term_id": 15
},
"1": {
"term_id": 20
},
}
}
},
{
"name": "new post 2",
"description": "simple desc 2",
"taxonomies": {
"categories": {
"0": {
"term_id": 11
},
"1": {
"term_id": 12
},
}
}
}
];
const filterID = [15, 1];
const resultPost = post.filter(post => {
if ((post.taxonomies.categories.filter(postct => postct.term_id === filterID)).length > 0) return post
});
console.log(resultPost);
You could filter the posts by matching the taxonomies.categories[id].term_id as follows:
const post = [{
"name": "new post",
"description": "simple desc",
"taxonomies": {
"categories" : {
"0" : {
"term_id" : 15
},
"1" : {
"term_id" : 20
},
}
}
},
{
"name": "new post 2",
"description": "simple desc 2",
"taxonomies": {
"categories" : {
"0" : {
"term_id" : 11
},
"1" : {
"term_id" : 12
},
}
}
}];
const filterID = [15,1];
const resultPost = post.filter(item => {
const { categories } = item.taxonomies;
return Object.keys(categories).reduce((cats, id) => {
filterID.includes(categories[id].term_id) && cats.push(id);
return cats;
}, []).length
});
console.log( resultPost)
Like said in comments, you can't use filter on an Object.
Try this instead
const resultPost = post.filter(post => {
for (let cat in post.taxonomies.categories) { // one way to loop over objects
// filterId is an array so you can't just use ===
if (filterID.includes(post.taxonomies.categories[cat].term_id)) return true;
}
return false;
});
Inside filter, you can take Object.values of that object and then use some based on your condition to filter out records. Something like this:
const post = [{ "name": "new post", "description": "simple desc", "taxonomies": { "categories": { "0": { "term_id": 15 }, "1": { "term_id": 20 }, } } }, { "name": "new post 2", "description": "simple desc 2", "taxonomies": { "categories": { "0": { "term_id": 11 }, "1": { "term_id": 12 }, } } }];
const filterID = [15,1];
const result = post.filter(p=>Object.values(p.taxonomies.categories).some(n=>filterID.includes(n.term_id)));
console.log(result);

How can I read a node in txt file using Javascritp

I need create a list like
ANIMAL 1
ANIMAL 2
ANIMAL 3
And the response is in a .TXT file with some nodes
{
"pets":[
{ "animal":"animal 1", "name":"Fido" },
{ "animal":"animal 2", "name":"Felix" },
{ "animal":"animal 3", "name":"Lightning" }
]
}
How can I create a JS to return the name of the animal in a DIV?
There's probably a better approach for this than what I did, but it's something.
Your can iterate through your object with a for loop like this:
const response = {
"pets": [{
"animal": "animal 1",
"name": "Fido"
},
{
"animal": "animal 2",
"name": "Felix"
},
{
"animal": "animal 3",
"name": "Lightning"
}
]
};
// Loop through the pets property of the response object
for (let i = 0; i < response.pets.length; i++) {
// Add the name property of the pets property to the div
document.getElementById('animals').innerHTML += `${response.pets[i].name} <br>`;
}
<div id="animals"></div>
Check the following code..hope it helps :)
let response = {
"pets": [{
"animal": "animal 1",
"name": "Fido"
},
{
"animal": "animal 2",
"name": "Felix"
},
{
"animal": "animal 3",
"name": "Lightning"
}
]
}
function getAnimals() {
let html = '';
response.pets.forEach(animal => {
html += `<div>${animal.name}</div>`;
});
console.log(html)
}
getAnimals();

JS map two object/array

I have 2 objects with format:
obj1 = [
{
"code": "in_today",
"text": "Today"
},
{
"code": "in_week",
"text": "This week"
},
{
"code": "in_month",
"text": "This month"
},
{
"code": "normal",
"text": "Other"
}
]
obj2 stores "code" value which defined in obj1:
obj2 = ["in_today", "in_week", "normal"]
How can I use obj2's values to change obj1 into something likes:
[
{
"code": "in_today",
"text": "Today",
"selected": true
},
{
"code": "in_week",
"text": "This week",
"selected": true
},
{
"code": "in_month",
"text": "This month",
"selected": false
},
{
"code": "normal",
"text": "Other"
"selected": true
}
]
What's the best solution for this case?
Thanks!
You can use Array.map to transform your objects based on whether their code is in the obj2 array:
var obj1 = [
{
"code": "in_today",
"text": "Today"
},
{
"code": "in_week",
"text": "This week"
},
{
"code": "in_month",
"text": "This month"
},
{
"code": "normal",
"text": "Other"
}
]
var obj2 = ["in_today", "in_week", "normal"]
var newObject = obj1.map(function(obj) {
if (obj2.indexOf(obj.code) > -1) {
obj.selected = true;
} else {
obj.selected = false;
}
return obj;
})
console.log(newObject)
Or a bit simpler if ES6 is available:
const newObject = obj1.map((obj) => {
obj.selected = obj2.includes(obj.code);
return obj;
})
Simple&quick solution using Array#forEach.
var obj1 = [{"code":"in_today","text":"Today"},{"code":"in_week","text":"This week"},{"code":"in_month","text":"This month"},{"code":"normal","text":"Other"}],
obj2 = ["in_today", "in_week", "normal"];
obj1.forEach(v => v.selected = obj2.indexOf(v.code) > -1);
console.log(obj1);
You'll want to do something like this:
for (var i = 0; i < obj1.length; ++i) {
if (obj2.indexOf(obj1[i].code) == -1) {
obj1[i].selected = false;
} else {
obj1[i].selected = true;
}
}
Essentially, you just loop over obj1, then check if the value of obj1.code is present in obj2, then set selected accordingly.
obj1 = [
{
"code": "in_today",
"text": "Today"
},
{
"code": "in_week",
"text": "This week"
},
{
"code": "in_month",
"text": "This month"
},
{
"code": "normal",
"text": "Other"
}
]
obj2 = ["in_today", "in_week", "normal"];
obj1.forEach( function(elem){
if( obj2.indexOf(elem.code) > -1)
elem.selected = true;
else
elem.selected = false;
});
console.log( JSON.stringify(obj1) );

How to iterate an object and build a new one

I am using JavaScript to iterate customers in an object which is constructed as follows:
[
{
"customer": "Customer 1",
"project": "1"
},
{
"customer": "Customer 2",
"project": "2"
},
{
"customer": "Customer 2",
"project": "3"
}
]
I wish to build a new object in iteration which would be constructed like this:
[
{
"Customer 1": {
"projects": "1"
}
},
{
"Customer 2": {
"projects": [
"2",
"3"
]
}
}
]
Any tips how this could be achieved?
You can create an intermediate object to form the inner level object. Use the iterator on that object to form the array out of it.
Please refer below for sample code.
var response = [
{
"customer": "Customer 1",
"project": "1"
},
{
"customer": "Customer 2",
"project": "2"
},
{
"customer": "Customer 2",
"project": "3"
}
];
var length = response.length,
i = 0,
result = {},
j = 0,
finalResult = [];
for(;i<length;i++){
var eachObj = response[i];
if(!result[response[i].customer]){
result[response[i].customer] = [response[i].project];
}
else{
result[response[i].customer].push(response[i].project);
}
}
for(var key in result){
var eachObj = [];
eachObj[key] = result[key];
finalResult.push(eachObj);
}
console.log(finalResult);
Lookup in new array for customer and if found add project, otherwise add customer.
var data = [
{
"customer": "Customer 1",
"project": "1"
},
{
"customer": "Customer 2",
"project": "2"
},
{
"customer": "Customer 2",
"project": "3"
}
];
var newData = [];
data.forEach(function (el, i) {
var customer = newData.filter(function (ell) {
return el.customer === ell.customer;
})[0];
if (customer) {
customer.projects.push(el.project);
} else {
newData.push({ customer: el.customer, projects: [el.project] });
}
});
document.write('<pre>' + JSON.stringify(newData, null, 4) + '</pre>');

value got overwritten assigning json value within loop

How can I produce something like this?
{
"drink": {
"2": {
"name": "coke",
"type": "drink"
},
"3": {
"name": "coke",
"type": "drink"
}
},
"food": {
"id": "1",
"name": "1 Hour Snooker",
"type": "food"
}
}
I have problem producing multiple object under 'drink' object. It got overwritten with my below code:
http://jsfiddle.net/jLgh4at5/
var json = {
"results": {
"slots": [{
"id": "3",
"name": "pepsi",
"type": "drink"
}, {
"id": "1",
"name": "1 Hour Snooker",
"type": "food"
}, {
"id": "2",
"name": "coke",
"type": "drink"
}]
}
}
var data = {
"slots": {
}
}
json.results.slots.forEach(function (b) {
if (b["type"] == "food") {
data.slots["food"] = b;
} else {
data.slots["drink"] = b;
}
});
console.log(data);
Use array index to resolve the issue.
json.results.slots.forEach(function (b,i) {
if (b["type"] == "food") {
if(data.slots["food"])
data.slots["food"][i] = {"name":b.name,"type":"food"};
else
data.slots["food"] = {};
} else {
if(data.slots["drink"])
data.slots["drink"][i] = {"name":b.name,"type":"drink"};
else
data.slots["drink"] = {};
}
});
Or you can optimize the code as shown below.
var data = {
"slots": {
"food": {},
"drink": {}
}
};
json.results.slots.forEach(function (b,i) {
if (b["type"] == "food") {
data.slots["food"][i] = {"name":b.name,"type":"food"};
} else {
data.slots["drink"][i] = {"name":b.name,"type":"drink"};;
}
});
Here is the updated JSFiddle

Categories

Resources