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

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;

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

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

Javascript map is not a function what trying to read data

I am trying to populate a chart so I'm getting the data into 2 lists in order to do this.
This is the data:
var data = [{
"id": "622",
"name": "some name",
"boats": {
"637": {
"id": "637",
"name": " Subcat 1",
"translations": null
},
"638": {
"id": "638",
"name": "Subcat 2",
"translations": null
}
},
"image": "73e043a7fae04b55855bede22da6286b"
}];
And I am running this code in order to populate the lists:
var chList = [];
var boatList = [];
var boatCount = [];
for (var i = 0; i < data.length; i++) {
var obj = data[i];
var cl = obj.name + " [" + obj.id + "]";
if (obj.boats != null) {
chList.push(cl);
}
if(obj.boats) {
var nme = obj.boats.map( function(item){
return item.name;
});
boatList = boatList.concat(nme);
boatCount.push(nme.length);
}
}
console.log(boatList);
console.log(boatCount);
My problem is that I keep getting:
TypeError: obj.boats.map is not a function
How can I fix this?
Note: The data is actually this:
{
"id": "622",
"name": "some name",
"boats": {
"637": {
"id": "637",
"name": " Subcat 1",
"translations": null
},
"638": {
"id": "638",
"name": "Subcat 2",
"translations": null
}
},
"image": "73e043a7fae04b55855bede22da6286b"
};
But I added [ and ] to it in order to use data.length and the lists where empty too ... Do I then leave this data as it is?
The problem is that obj.boats is an object, not an array, hence doesn't have the map method.
Try this instead:
Object.keys(obj.boats).map(function(k) { return obj.boats[k].name; });
See MDN
boats is an object, not an array. Map is for arrays.
You could use a for ( in ) loop or Object.keys() to get an array of keys and work with that.
The two other answers are right, I'd change the data though:
"boats": [
{
"id": "637",
"name": " Subcat 1",
"translations": null
},
{
"id": "638",
"name": "Subcat 2",
"translations": null
}
],
Using the id as key and then giving the containing object a "id" property is kinda pointless. When you change the data to this structure your code will work fine.
Besides all other answers that already correctly point to obj.boats being an Object and not an Array, I'd like providing a solution that demonstrates the elegant beauty of Array.reduce ...
var boatChartData = [{
"id": "622",
"name": "some name",
"boats": {
"637": {
"id": "637",
"name": "Subcat 1",
"translations": null
},
"638": {
"id": "638",
"name": "Subcat 2",
"translations": null
}
},
"image": "73e043a7fae04b55855bede22da6286b"
}, {
"id": "623",
"name": "other name",
"boats": {
"639": {
"id": "639",
"name": "Supercat",
"translations": null
},
"640": {
"id": "640",
"name": "Supercat II",
"translations": null
},
"641": {
"id": "641",
"name": "Supercat III",
"translations": null
}
},
"image": "73e043a7fae04b55855bede22da6295c"
}];
function collectBoatChartData(collector, chartItem/*, idx, list*/) {
var
boatNameList,
boatMap = chartItem.boats;
if (boatMap != null) {
collector.chartItemTitleList.push([
chartItem.name,
" [",
chartItem.id,
"]"
].join(""));
boatNameList = Object.keys(boatMap).map(collector.getBoatNameByKey, boatMap);
collector.boatNameList = collector.boatNameList.concat(boatNameList);
//collector.chartItemBoatNameList.push(boatNameList);
collector.chartItemBoatCountList.push(boatNameList.length);
}
return collector;
}
var processedBoatChartData = boatChartData.reduce(collectBoatChartData, {
getBoatNameByKey: function (key) {
return this[key].name;
},
boatNameList: [],
chartItemTitleList: [],
//chartItemBoatNameList: [],
chartItemBoatCountList: []
});
console.log("processedBoatChartData.boatNameList : ", processedBoatChartData.boatNameList);
console.log("processedBoatChartData.chartItemTitleList : ", processedBoatChartData.chartItemTitleList);
//console.log("processedBoatChartData.chartItemBoatNameList : ", processedBoatChartData.chartItemBoatNameList);
console.log("processedBoatChartData.chartItemBoatCountList : ", processedBoatChartData.chartItemBoatCountList);
Note
Taking into account the OP's additional comment, mentioning the provided axample's real data structure, the above provided solution of mine just changes to ...
var boatChartData = {
"id": "622",
"name": "some name",
"boats": {
"637": {
"id": "637",
"name": "Subcat 1",
"translations": null
},
"638": {
"id": "638",
"name": "Subcat 2",
"translations": null
}
},
"image": "73e043a7fae04b55855bede22da6286b"
};
var processedBoatChartData = [boatChartData].reduce(collectBoatChartData, {
getBoatNameByKey: function (key) {
return this[key].name;
},
boatNameList: [],
chartItemTitleList: [],
//chartItemBoatNameList: [],
chartItemBoatCountList: []
});
.., proving that generic solutions can be recycled/adapted easily, if e.g. data structures do change.

Javascript Array count and add result to variable

I have an array like this:
var obj = {
"people": [{
"id": "100",
"name": "name 1",
"desc": "desc 1",
"class": "a"
}, {
"id": "192",
"name": "name 2",
"desc": "desc 2",
"class": "b"
}, {
"id": "324",
"name": "name 3",
"desc": "desc 3",
"class": "b"
}, {
"id": "324",
"name": "name 4",
"desc": "desc 4",
"class": "a"
}, {
"id": "324",
"name": "name 5",
"desc": "desc 5",
"class": "a"
}]
};
I know that for example, in order to get all the records with class "a" I do this:
obj.people.filter(function(item) { return item.class === "a" });
But How can I count to total number of records that contain class "a" ?
You could use the Array#length property from the returned array.
count = obj.people.filter(function(item) { return item.class === "a" }).length;
Or use Array#reduce and add the comparison.
count = obj.people.reduce(function (r, item) { return r + +(item.class === "a") }, 0);
Just check the length of array returned by the filter
var result = obj.people.filter(function(item) { return item.class === "a" });
console.log( result.length );
or you can simply run a loop that tells you this count
var count = 0;
for( var counter = 0; counter < obj.people.length; counter++ )
{
( obj.people[ counter ].class === "a" ) && count++;
}
console.log( count );

Categories

Resources