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 );
Related
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);
I am trying to sort this array by timestamp values. I want to sort them in ascending order and if any of them have an indefinite property, place it at the end. I currently have the error Cannot read property 'first_release_date' of undefined. How to solve this?
var array =
[
{
"id": 1969,
"cover": {
"id": 1960,
"url": "image.jpg"
},
"first_release_date": 1083542400,
"name": "Item 1"
},
{
"id": 113242,
"name": "Item 2"
},
{
"id": 25076,
"first_release_date": 1540512000,
"name": "Item 3"
},
{
"id": 1969,
"cover": {
"id": 1960,
"url": "image.jpg"
},
"name": "Item 4"
},
{
"id": 9245,
"first_release_date": 1292976000,
"name": "Item 5"
}
];
Object.keys(array).forEach((key) => {
console.log(`Before: ${array[key].name}`)
});
array.sort((a,b) => a.array.first_release_date > b.array.first_release_date);
Object.keys(array).forEach((key) => {
console.log(`After: ${array[key].name}`)
});
You are almost there. Only need to provide a default value for when there's no date. Also, sort requires you to return a number, at the moment you return a boolean, which will be cast to 0 or 1. Which will break the sort for the cases you want to return a negative number.
var array =
[
{
"id": 1969,
"cover": {
"id": 1960,
"url": "image.jpg"
},
"first_release_date": 1083542400,
"name": "Item 1"
},
{
"id": 113242,
"name": "Item 2"
},
{
"id": 25076,
"first_release_date": 1540512000,
"name": "Item 3"
},
{
"id": 1969,
"cover": {
"id": 1960,
"url": "image.jpg"
},
"name": "Item 4"
},
{
"id": 9245,
"first_release_date": 1292976000,
"name": "Item 5"
}
];
Object.values(array).forEach((val) => {
var d = new Date(val.first_release_date*1000).getFullYear();
console.log(`Before: ${ val.name} ${d }`)
});
array.sort((a,b) => ( a.first_release_date || Number.POSITIVE_INFINITY ) - ( b.first_release_date || Number.POSITIVE_INFINITY ));
Object.values(array).forEach((val) => {
var d = new Date(val.first_release_date*1000).getFullYear();
console.log(`After: ${ val.name} ${d }`)
});
var reverse = JSON.parse( JSON.stringify( array ));
reverse.sort((a,b) => ( b.first_release_date || Number.NEGATIVE_INFINITY ) - ( a.first_release_date || Number.NEGATIVE_INFINITY ));
console.log( reverse );
I have some data and I need to filter out the data thats null or empty and create a new data list thats filtered.
In this case sometimes "names" array is null so I need that data out.
{
"people": [
{
"id": "2",
"description": "desc here",
"names": [
{
"name": "name here",
},
{
"name": "name here",
}
],
"other": "0"
},
{
"id": "200",
"description": "desc here",
"names": null
"other": "0"
},
{
"id": "64",
"description": "desc here",
"names": [
{
"name": "name here",
},
{
"name": "name here",
}
],
"other": "1"
}
]
}
How can I do this?
You could iterate the arrays and objects recursive until a primitive is found. Then check and return the value.
function copy(object) {
var o;
if (Array.isArray(object)) {
return object.reduce(function (r, a) {
var v = copy(a);
v.names !== null && v.names !== '' && r.push(v);
return r;
}, []);
}
if (object !== null && typeof object === 'object') {
o = {};
Object.keys(object).forEach(function (k) {
o[k] = copy(object[k]);
});
return o;
}
return object;
}
var data = { people: [{ id: "2", description: "desc here", names: [{ id: "345", name: "name here", }, { id: "54", name: "name here", foo: "", }], other: "0" }, { id: "2", description: "desc here", names: null, other: "0" }, { id: "64", description: "desc here", names: [{ id: "87", name: "name here", }, { id: "53", name: "name here", }], other: "1" }] },
result = copy(data);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
var newArray = oldArray.filter(function(v){return v!==''});
new_array=yourObject.people.filter(function(elem){
return elem.names!==null && elem.names!==""
});
I have the following object
{
"locations": {
"Base 1": {
"title": "This is base 1",
"Suburb 1": {
"title": "Suburb 1 in Base 1",
"Area A": {
"title": "Title for Area A",
"Street S1": {
"title": "Street S1 title"
},
"Street C4": {
"title": "Street C4 title"
},
"Street B7": {
"title": "Street B7 title"
}
},
"Another Area": {
"title": "Title for Area A",
"Street S1": {
"title": "Street S1 title"
},
"Street C4": {
"title": "Street C4 title"
},
"Street B7": {
"title": "Street B7 title"
}
}
},
"Another Suburb": {
"title": "Suburb 1 in Base 1",
"Area A": {
"title": "Title for Area A",
"Street S1": {
"title": "Street S1 title"
},
"Street C4": {
"title": "Street C4 title"
},
"Street B7": {
"title": "Street B7 title"
}
},
"Another Area": {
"title": "Title for Area A",
"Street S1": {
"title": "Street S1 title"
},
"Street C4": {
"title": "Street C4 title"
},
"Street B7": {
"title": "Street B7 title"
}
}
}
},
"Base2": {}
}
}
I'm given arrays to fetch "titles" from the "locations" object and each array can be different. I know I can access individual values like so :
locations["Base 1"]["title"]
locations["Base 1"]["Another Suburb"]["title"]
locations["Base 1"]["Another Suburb"]["Area A"]["title"]
etc etc.
But I'm not sure how to get the value of title if I'm given arrays like so :
AnArray = ["Base 1", "title"];
AnArray = ["Base 1", "Another Suburb", "title"];
AnArray = ["Base 1", "Another Suburb", "Area A", "title"];
AnArray = ["Base 1", "Another Suburb", "Another Area", "title"];
Is there a way to parse / work with these arrays so each returns the correct title value from the locations object?
I have to fetch the value of the title in each case, and I'm not even sure where to start. I tried joining the array and then fetching the 'title' values but that didn't seem to work.
Noob here, so please don't mind if the question sounds stupid / or makes no sense.
So the question is, how do I fetch values from a hierarchical object when the references are in an array ?
function getNested(obj, ar_keys) {
var innerObj = obj;
for(var i=0,il=ar_keys.length; i<il; i++){
innerObj = innerObj[ar_keys[i]];
}
return innerObj;
}
You would call it with
getNested(x['locations'], ar_keys);
where x is your object and ar_keys is the array of keys.
I suppose you need something like that:
iterate through every array
iterate through the values of the array
for each value nest one level deeper into the object
store the final values in an array
Try this:
var arrays = [
["Base 1", "title"],
["Base 1", "Another Suburb", "title"],
["Base 1", "Another Suburb", "Area A", "title"],
["Base 1", "Another Suburb", "Another Area", "title"]
],
array, i, j,
obj = {
"locations": {
"Base1": {
"title": "Thisisbase1",
"Suburb1": {
"title": "Suburb1inBase1",
"AreaA": {
"title": "TitleforAreaA",
"StreetS1": {
"title": "StreetS1title"
},
"StreetC4": {
"title": "StreetC4title"
},
"StreetB7": {
"title": "StreetB7title"
}
},
"AnotherArea": {
"title": "TitleforAreaA",
"StreetS1": {
"title": "StreetS1title"
},
"StreetC4": {
"title": "StreetC4title"
},
"StreetB7": {
"title": "StreetB7title"
}
}
},
"AnotherSuburb": {
"title": "Suburb1inBase1",
"AreaA": {
"title": "TitleforAreaA",
"StreetS1": {
"title": "StreetS1title"
},
"StreetC4": {
"title": "StreetC4title"
},
"StreetB7": {
"title": "StreetB7title"
}
},
"AnotherArea": {
"title": "TitleforAreaA",
"StreetS1": {
"title": "StreetS1title"
},
"StreetC4": {
"title": "StreetC4title"
},
"StreetB7": {
"title": "StreetB7title"
}
}
}
},
"Base2": {}
}
},
current, key,
result = [];
for (i = 0; i < arrays.length; i++) {
array = arrays[i];
// reset current to the locations object
current = obj.locations;
for (j = 0; j < array.length; j++) {
// remove spaces from the keys
key = array[j].replace(' ', '', 'gi');
if (current[key]) {
// if there is such key then nest further
current = current[key];
} else {
// there is no such key - log it
console.log(key);
}
}
if (typeof current === "string") {
// if you have reached a string with the nesting add it to the result
result.push(current);
}
}
// output the final result
console.log(result);
In my case it outputs:
["Thisisbase1", "Suburb1inBase1", "TitleforAreaA", "TitleforAreaA"]
I have added additional logging so it is clear if something with the keys goes wrong.
If the arrays are 'paths' to the required title you could do it this way.
Note that 'locations' is required in this case as it's the start of the path and title is not required since we're always looking for it.
var path = ["locations", "Base1", "AnotherSuburb"];
(function search(o, a){
for(var p in o){
if(typeof o[p] === 'object' && path.indexOf(p) !== -1){
a.push(p);
if(a.join('') === path.join('')){
// match, print the title
console.log(o[p].title);
}
else{
search(o[p], a);
}
}
}
})(object, []);
Will print Suburb1inBase1
Demo: http://jsfiddle.net/louisbros/Fq63D/
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;