How can I read a node in txt file using Javascritp - javascript

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();

Related

How to reformat object using its property value as property key?

how can I assign object property value as property key?
I have a set of data:
const mydata = [
{
"id": 001,
"value": "Value 1",
"title": "Title 1"
},
{
"id": 002,
"value": [
{
"Name": "Name 1",
"Age": "20"
},
{
"Name": "Name 2",
"Age": "30"
},
],
"title": "Title 2"
},
]
I want to reformat it to become:
const mydata = [
{
"Title 1": "Value 1"
},
{
"Title 2": [
{
"Name": "Name 1",
"Age": "20"
},
{
"Name": "Name 2",
"Age": "30"
},
]
},
]
I have tried this code to achieve it:
mydata.map((dt: any) => {
dt.title: dt.value
});
However, it seems not working.
Any idea how can I reformat it to the one I desire?
Thanks.
Please use following code.
Reference URL How to use a variable for a key in a JavaScript object literal?
const mydata = [
{
"id": 001,
"value": "Value 1",
"title": "Title 1"
},
{
"id": 002,
"value": [
{
"Name": "Name 1",
"Age": "20"
},
{
"Name": "Name 2",
"Age": "30"
},
],
"title": "Title 2"
},
];
let reData = [];
mydata.forEach((dt)=>{
reData.push({[dt.title]: dt.value});
});
console.log(reData);
If you want to transform the array to a different type of variable, use [reduce][1]
const mydata = [
{
id: 001,
value: "Value 1",
title: "Title 1",
},
{
id: 002,
value: [
{
Name: "Name 1",
Age: "20",
},
{
Name: "Name 2",
Age: "30",
},
],
title: "Title 2",
},
];
const data = mydata.reduce(
(acc, cur) => ({ ...acc, [cur.title]: cur.value }),
{}
);
console.log(data);
Your map function has an error, and your key assignment has another one. Let's fix it.
const newData = mydata.map((dt: any) => ({
[dt.title]: dt.value,
}));
First: You can't return an object from an arrow function without parenthesis, if you don't use it, the code will think it is a function body not an object.
Second: If you want to return a value as a key, you need put it inside "[ ]" (Square brackets)
Just that, simple mistakes, at the end you came up with the right logic to solve it
Add brackets around the return value.
Use square brackets for a computed property name.
const mydata = [
{
"id": 001,
"value": "Value 1",
"title": "Title 1"
},
{
"id": 002,
"value": [
{
"Name": "Name 1",
"Age": "20"
},
{
"Name": "Name 2",
"Age": "30"
},
],
"title": "Title 2"
},
];
const res = mydata.map(({value, title})=>({[title]: value}));
console.log(res);

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);

Filtration of multilevel JSON array

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);

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>');

how to get the user id from this array and print that

i have code to get the my friend list from facebook
the code is................
function getFriends() {
//if the person has not pressed login button
if(!loggedIn) {
loginFacebook();
}
document.getElementById("status").innerHTML = "Now loading your friends' id...";
//if the person is loggedIn
if(loggedIn) {
document.getElementById("friendBtn").disabled = "disabled";
FB.api("/me/friends",function(response){
friends = response["data"];
totalToBeLoaded = friends.length;
// addNewRow("Name","id");
loadid(friends.length);
});
}
}
the response["data"] function returns the data in the form of array as
{
"data": [
{
"name": "name 1",
"id": "123456781"
},
{
"name": "name 2",
"id": "123456782"
},
{
"name": "name 3",
"id": "123456783"
},
{
"name": "name 4",
"id": "123456784"
},
{
"name": "name 5",
"id": "123456785"
},
{
"name": "name 6",
"id": "123456786"
}
]
}
now i need to get that name and id of the user from that response["data"] and print that .. how to do that?
Its an array of objects. You can use the following:
var list=response["data"];
for(var i=0;i<list.length;i++) {
addUser(list[i].name, list[i].id);
}
EDIT:
Even first line can be written as
var list=reponse.data;

Categories

Resources