JSON in list JS [duplicate] - javascript

This question already has answers here:
Iterating Array of Objects in javascript
(9 answers)
Closed 3 years ago.
have file_name.JSON, like
[{"id": 1},{"id": 2},{"id": 3}]
How can I use "for" to get in final:
1,2,3
const file_name = [{
"id": 1
}, {
"id": 2
}, {
"id": 3
}]
for (let i = 0; i <= file_name.length; i++) {
console.log(file_name[i].id);
}
Or maybe another way, not use "for"

To fix your code you need just to change i <= file_name.length to i < file_name.length
const file_name = [{
"id": 1
}, {
"id": 2
}, {
"id": 3
}]
for (let i = 0; i < file_name.length; i++) {
console.log(file_name[i].id);
}
Or for a better and clean code you can use map
const file_name = [{
"id": 1
}, {
"id": 2
}, {
"id": 3
}]
const res = file_name.map(({
id
}) => console.log(id));

Use map
const file_name = [{
"id": 1
}, {
"id": 2
}, {
"id": 3
}]
let arr = file_name.map(e => e.id);
console.log(arr);
let str = file_name.map(e => e.id).join();
console.log(str);

No, you don't have JSON, you have a plain old Javascript array there.
var file_name = [{"id": 1},{"id": 2},{"id": 3}];
var justNumbers = file_name.map(e => e.id);
console.log(justNumbers);

Related

How would I filter an array of objects by : If id numbers are consecutive

I have a JSON file that has an array of objects with data inside :
[
{
"_id": "62bd5fba34a8f1c90303055c",
"index": 0,
"email": "mcdonaldholden#xerex.com",
"nameList": [
{
"id": 0,
"name": "Wendi Mooney"
},
{
"id": 2,
"name": "Holloway Whitehead"
}
]
},
{
"_id": "62bd5fbac3e5a4fca5e85e81",
"index": 1,
"nameList": [
{
"id": 0,
"name": "Janine Barrett"
},
{
"id": 1,
"name": "Odonnell Savage"
},
{
"id": 2,
"name": "Patty Owen"
}
]
}, ...
My job is to filter the arrays that have more than two names and if their id are consecutive.
I managed to sort users with more than two user.name but cant grasp the concept of filtering consecutive id numbers
let lister3 = userData.filter(names => names?.nameList?.filter(name => name?.name).length > 2)
Which returns me the objects with more than two user names.
filter takes a function that returns true if you want to retain the item or false if not. In this function, you could check the length of the nameList, and then iterate over its members and make sure their ids are consecutive:
retult = userData.filter(u => {
if (u.nameList.length < 2) {
return false;
}
for (let i = 1; i < u.nameList.length; ++i) {
if (u.nameList[i].id != u.nameList[i - 1].id + 1) {
return false;
}
}
return true;
});
a item should need tow conditions,one is nameList length is two ,the other is the itemId of nameList is consecutive;
so first as you do :
`
let lister3 = userData.filter(names => names?.nameList?.filter(name => name?.name).length > 2)
`
;
then
`
let lister4 = lister3.filter(names=>{
let idOfStr = names.nameList?.sort((a,b)=>a.id-b.id).map(item=>item.id).join("");
let resultStr = Array.from(idOfStr.length).fill(+idOfStr[0]).map((item,index)=>+item+index).join('');
return idOfStr === resultStr
})
`
hope this is useful for you

Javascript - Get occurence of json array with ESLINT 6

I can't set up an algo that counts my occurrences while respecting ESlint's 6 standards in javascript.
My input table is :
[
{
"id": 2,
"name": "Health",
"color": "0190fe"
},
{
"id": 3,
"name": "Agriculture",
"color": "0190fe"
},
{
"id": 1,
"name": "Urban planning",
"color": "0190fe"
},
{
"id": 1,
"name": "Urban planning",
"color": "0190fe"
}
]
And i want to get :
{"Urban planning": 2, "Health": 1, ...}
But that does not work with ESLINT / REACT compilation...
This is my code :
const jsonToIterate = *'MyPreviousInputJson'*
const names = []
jsonToIterate.map(item => (names.push(item.name)))
const count = []
names.forEach(item => {
if (count[item]){
count.push({text: item, value: 1})
} else {
count.forEach(function(top){top.text === item ? top.value =+ 1 : null})
}
})
Thank you so much
Well, you want an object in the end, not an array, so count should be {}. I also wouldn't use map if you're not actually returning anything from the call. You can use reduce for this:
let counts = topicsSort.reduce((p, c, i, a) => {
if (!p.hasOwnProperty(c.name)) p[c.name] = 0;
p[c.name]++;
return p;
}, {});
I'm half exppecting someone to close this as a duplicate because all you've asked for is a frequency counter. But here's an answer anyway:
const jsonToIterate = *'MyPreviousInputJson'*;
const names = {};
jsonToIterate.map(obj => {
if(obj.name in names){
names[obj.name]++
}
else{
names[obj.name] = 1;
}
})

print full path javascript

This is the result I am getting from my database when I do a query:
[
{
"name": "file1.txt",
"id": 1,
"file_path": "./public/files/file1.txt"
}
{
"name": "file3.txt",
"id": 3,
"file_path": "./public/files/file3.txt"
},
{
"name": "file4.txt",
"id": 8,
"file_path": "./public/files/file4.txt"
},
{
"name": "file5.txt",
"id": 7,
"file_path": "./public/files/file5.txt"
}
]
And what I want to print is this kinda of format of file path ./public/files/file1.txt
This is what I am trying right now but it doesn't seem to work:
var paths = [];
if(result.length > 0) {
var tmp_path = result[0].file_path
var count = 0
result.forEach(element => {
count++
tmp_path = element.file_path
paths.push(decodeURI(tmp_path))
})
console.log(JSON.stringify(paths,null,4))
}
The result I get is this:
[
"./public/files/file1.txt",
"./public/files/file3.txt",
"./public/files/file4.txt",
"./public/files/file5.txt",
]
Isn't decodeURI() the function I am supposed to use in this case?
I am working on Node.js with router and ejs npms. So this is part of a get function and the result will be populated in front-end with ejs. So what I am trying to do is to pass the correct format on the result which is PATHS
You can tweak your code so that that file path is saved as a HTML content in a element say, div then get the HTML from this element to get the decoded value and push it into the array.
var result = [
{
"name": "1k",
"id": 1,
"file_path": "./public/files/file1.txt"
},
{
"name": "3k",
"id": 3,
"file_path": "./public/files/file3.txt"
},
{
"name": "4k",
"id": 8,
"file_path": "./public/files/file4.txt"
},
{
"name": "5k",
"id": 7,
"file_path": "./public/files/file5.txt"
}
];
var paths = [];
if(result.length > 0) {
var tmp_path = result[0].file_path
var count = 0
result.forEach(element => {
count++;
tmp_path = element.file_path;
var elem = document.createElement('div');
elem.innerHTML = tmp_path;
paths.push(elem.innerHTML);
})
console.log(JSON.stringify(paths,null,4))
}
Not sure if this would work for you, but you can use a .map to remap the array into an array of strings making slight adjustments:
So for each file_path split with ';' then take the last element of the split 'filei.text' and concatenate './public/files/' before it.
const res = data.map(e => {
const path = e.file_path.split(';');
const fileName = path[path.length-1];
return './public/files/' + fileName;
});
const data = [
{
"name": "1k",
"id": 1,
"file_path": "./public/files/file1.txt"
},
{
"name": "3k",
"id": 3,
"file_path": "./public/files/file3.txt"
},
{
"name": "4k",
"id": 8,
"file_path": "./public/files/file4.txt"
},
{
"name": "5k",
"id": 7,
"file_path": "./public/files/file5.txt"
}
];
const res = data.map(e => {
const path = e.file_path.split(';');
const fileName = path[path.length-1];
return './public/files/' + fileName;
});
console.log(res)
You can use decodeURI() in the following way
var uri = "./public/files/file1.txt";
var enc = encodeURI(uri);
var dec = decodeURI(enc);
You can show this URL in html like below:
document.getElementById("demo").innerHTML = dec;
just encode the file_path with encodeURI you will get original url
e.g.:
var uri = "./public/files/file1.txt";
console.log(encodeURI(uri));
Will return:
"./public/files/file1.txt"

Filtering an array of objects by a field [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I have an array of objects that each contain two categories, one of these categories represents a group.
[
{
"uuid": 123,
"group": "test_group"
},
{
"uuid": 321,
"group": "test_group"
},
{
"uuid": 432,
"group": "test_group2"
}
]
I'm looking to generate a JSON response that has categorized them by their groups.
{
"objects": [
{
"group": "test_group",
"items": [
{
"uuid": 123
},
{
"uuid": 321
}
]
},
{
"group": "test_group2",
"items": [
{
"uuid": 432
}
]
}
]
}
At the moment I've accomplished this by first iterating over and creating a set of all of the groups involved, and then iterating again and grouping them appropriately. I was wondering if there was a more succinct way of doing this, perhaps using some of the new operators introduced in ES6.
Iterate using Array#reduce, and collect the items by group into a Map. Use spread to convert the Map#values back into array:
const data = [
{
"uuid": 123,
"group": "test_group"
},
{
"uuid": 321,
"group": "test_group"
},
{
"uuid": 432,
"group": "test_group2"
}
];
const result = [...data.reduce((hash, { uuid, group }) => {
const current = hash.get(group) || { group, items: [] };
current.items.push({ uuid });
return hash.set(group, current);
}, new Map).values()];
console.log(result);
I don't know of there is a some new operator or an array function to make this easier introduced in ES6, however you could should be able to do it in a single iteration:
var arrayLength = myArray.length;
var response = {objects: []};
var groupIndex = {};
for (var i = 0; i < arrayLength; i++) {
let group = myArray[i].group;
if (!groupIndex.hasOwnProperty(group)) {
groupIndex[group] = groupIndex.length;
response.objects.push({
group: group,
items: [
{uuid: myArray[i].uuid}
]
}
else {
let index = groupIndex[group];
response.objects[index].items.push({uuid: myArray[i].uuid});
}
}

Compare two objects in jQuery and get the difference [duplicate]

This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 7 years ago.
Using jQuery I would like to compare 2 objects:
sourceArray:
var origArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 345
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
destination array
var destArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 888
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
What I would like to do, is compare the target object with the source object based on the ID and find the mis-matched entries with a description on the resultant object. So the result will look like this:
var resultArray = [{
"Name": "Double",
"URL": "yyy",
"ID": 888,
"desc": "missing in source"
},
{
"Name": "Double",
"URL": "yyy",
"ID": 345,
"desc": "missing in destination"
}];
Any quick help is really appreciated.
This isn't a good use of jQuery, but here is some vanilla javascript that does what you want.
function objDiff(array1, array2) {
var resultArray = []
array2.forEach(function(destObj) {
var check = array1.some(function(origObj) {
if(origObj.ID == destObj.ID) return true
})
if(!check) {
destObj.desc = 'missing in source'
resultArray.push(destObj)
}
})
array1.forEach(function(origObj) {
var check = array2.some(function(destObj) {
if(origObj.ID == destObj.ID) return true
})
if(!check) {
origObj.desc = 'missing in destination'
resultArray.push(origObj)
}
})
return resultArray
}
https://jsfiddle.net/9gaxsLbz/1/
If you are wanting to dedupe your array, this will work:
var merged = origArray.concat(destArray);
var unique = merged.filter(function(item) {
return ~this.indexOf(item.ID) ? false : this.push(item.ID);
}, []);
Fiddle: https://jsfiddle.net/Ljzor9c6/
If you are only wanting items that were duped, you can easily invert the condition:
var merged = origArray.concat(destArray);
var dupes = merged.filter(function(item) {
return ~this.indexOf(item.ID) ? true : !this.push(item.ID);
}, []);
You can loop through the items in the first array and put the ID's in a map, then loop through the items in the second array and remove the matching ID's and add the missing.
Then just loop through the map to create the objects in the resulting array:
var origArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 345
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
var destArray = [{
"Name": "Single",
"URL": "xxx",
"ID": 123
},
{
"Name": "Double",
"URL": "yyy",
"ID": 888
},
{
"Name": "Family",
"URL": "zzz",
"ID": 567
}];
var map = {};
for (var i = 0; i < origArray.length; i++) {
map[origArray[i].ID] = 'source';
}
for (var i = 0; i < destArray.length; i++) {
var id = destArray[i].ID;
if (id in map) {
delete map[id];
} else {
map[id] = 'destination';
}
}
var resultArray = [];
for (key in map) {
var arr = map[key] == 'source' ? origArray : destArray;
for (var i = 0; arr[i].ID != key; i++) ;
resultArray.push({
Name: arr[i].Name,
URL: arr[i].URL,
ID: arr[i].ID,
desc: 'missing in ' + map[key]
});
}
// show result in StackOverflow snippet
document.write(JSON.stringify(resultArray));
var result = [];
for(var i = 0; i < oa.length; i++) {
var idx = mIndexOf(oa[i].ID);
if(idx > -1) {
oa.splice(i, 1);
da.splice(idx, 1);
}
}
for(var i = 0; i < oa.length; i++) {
var ln = result.length;
result[ln] = oa[i];
result[ln].desc = "missing in destination";
}
for(var i = 0; i < da.length; i++) {
var ln = result.length;
result[ln] = da[i];
result[ln].desc = "missing in origin";
}
function mIndexOf(id) {
for(var i = 0; i < oa.length; i++)
if(oa[i].ID == id)
return i;
return -1;
}
console.log(result);
0: Object
ID: 345
Name: "Double"
URL: "yyy"
desc: "missing in destination"
1: Object
ID: 888
Name: "Double"
URL: "yyy"
desc: "missing in origin"
jsfiddle DEMO
For things like this, you should use lodash. With lodash you can just do this:
var resultArray = _.defaults(destArray, origArray);

Categories

Resources