I have json data like this image, which I got from PHP.
and I want to access all data from json.
for my current case, I want to match existing data with data from Json.
but i got a little error. all of my data is not same with Json data.
Though there must be some data that is suitable.
this my code
const dataArr = <?= $ar; ?>;
console.log(dataArr); //image 1
var mySVG = document.getElementById("alphasvg");
var svgDoc;
mySVG.addEventListener("load",function() {
svgDoc = mySVG.contentDocument.documentElement;
var xd = svgDoc.getElementsByTagName("rect");
for(i=0;i<xd.length;i++){
let get_a = xd[i].getAttribute('id');
for(x = 1; x<= 30; x++){
for(y=0; y<=4; y++){
if(get_a == 'rect' + x + '_child' + y){
//console.log(get_a); //img2
if(dataArr[(x-1)*y].idval.includes(get_a) == true){
console.log('yes u good');
} else {
console.log('error');
}
}
}
}
}
}, false);
can somone help me?
edit : resut of console.log(get_a,dataArr[(x-1)*y]);
my data is not matching.
If you simply want to search the objects inside the array for a particular occurence of a key - idval - and it's value you can use a simple for-loop like:
for (var a = 0; a < dataArr.length; a++) {
if (dataArr[a].idval == get_a) {
console.log("there it is", dataArr[a]);
break;
}
}
Here's an example:
var dataArr = [{
id: "test",
lantai: 1,
status_asrama: "tersedia",
idval: "rect_child1"
},
{
id: "anothertest",
lantai: 2,
status_asrama: "tersedia",
idval: "rect_child2"
}, {
id: "finaltest",
lantai: 3,
status_asrama: "tersedia",
idval: "rect_child3"
}
];
let get_a = "rect_child2";
for (var a = 0; a < dataArr.length; a++) {
if (dataArr[a].idval == get_a) {
console.log("there it is", dataArr[a]);
break;
}
}
Related
I have this mini CRUD in vanilla JS and HTML.
I need to be able to add or remove items and then list the array movies accordingly. I also need to do that without refreshing the page because of my hardcoded array.
I can't really call listMovies() every time a title is added or removed , otherwise I'd have multiple repetitions of the array displayed in the page.
Can anyone help me with a a solution for that?
This is my code:
window.onload = function () {
//Hard-coded array of movies - data.
// App is not connected to a database so everytime page is refreshed the array goes back to its original content.
var movies = [
'The Shawshank Redemption', 'The Godfather', 'Star Wars: Episode V - The Empire Strikes Back',
'Forrest Gump', 'The Perks of Being a Wallflower', 'The Dark Knight', 'Changeling', 'It\'s a Wonderful Life',
'The Silence of the Lambs', '8 Mile', 'The Breakfast Club', 'Django Unchained', 'Silver Linings Playbook',
'The Shining', 'Seven', 'American Beauty', 'Pulp Fiction', 'Zero Dark Thirty', 'Argo', 'The Hurt Locker'
];
// Variables for DOM manipulation
// var movieList = document.getElementById("movie-list__container");
var videoInput = document.getElementById("videoInput");
var addVideo = document.getElementById("addVideo");
var removeVideo = document.getElementById("removeVideo");
var alertMsg = document.getElementById("alertMsg");
var autocomplete = document.getElementById("autocomplete");
var searchResults = document.getElementById("search-results");
var movieListResults = document.getElementById("movie-list-results");
listMovies();
function listMovies() {
movies.sort();
for (i = 0; i < movies.length; i++) {
movieListResults.innerHTML += "<li>" + movies[i] + "</li>"
};
}
addVideo.onclick = addMovies;
function addMovies() {
var title = videoInput.value;
if (add(movies, title)) {
videoInput.value = "";
searchResults.innerHTML = '';
movieListResults.innerHTML += "<li>" + title + "</li>";
alertMsg.classList.remove("fail");
alertMsg.classList.add("success");
alertMsg.innerHTML = "Title was inserted successfully";
} else {
alertMsg.innerText = 'Please add a video title';
alertMsg.classList.remove("success");
alertMsg.classList.add("fail");
}
}
function add(data, title) {
if (title == "") {
return false;
} else {
data.push(title);
return true;
}
}
autocomplete.onkeyup = function () {
var results = [];
var userInput = this.value;
searchResults.innerHTML = "";
if (userInput != "") {
results = search(movies, userInput);
searchResults.style.display = "block";
if (results.length == 0) {
searchResults.innerHTML += "<li>Not found</li>";
searchResults.style.color = "grey";
} else {
searchResults.style.color = "black";
for (i = 0; i < results.length; i++) {
searchResults.innerHTML += "<li>" + results[i] + "</li>";
}
}
}
};
function search(data, input) {
var results = [];
for (i = 0; i < data.length; i++) {
if (input.toLowerCase() === data[i].slice(0, input.length).toLowerCase()) {
results.push(data[i]);
}
}
return results;
}
removeVideo.onclick = deleteMovie;
function deleteMovie() {
var title = videoInput.value;
if (title === "") {
alertMsg.innerHTML = 'Please enter the title you want to remove';
alertMsg.classList.add("fail");
} else {
if (remove(movies, title)) {
alertMsg.innerHTML = "Title has been successfully removed";
alertMsg.classList.add("success");
} else {
alertMsg.innerHTML = "Title not found";
alertMsg.classList.add("fail");
}
}
}
function remove(data, title) {
for (var i = 0; i < data.length; i++) {
if (title.toLowerCase() === data[i].toLowerCase()) {
data.splice(i, 1);
return true;
}
}
return false;
}
}; //End of window.onload
Nvm!
I figured it out by getting rid of the listMovies() and having the array printed once.
After that, I used a for loop for addMovie() and deleteMovie() to loop through the array and print it after the updates.
I realized that all I needed was to loop through the movies array and display the array again for both addMovie() and deleteMovie().
for (i = 0; i < movies.length; i++) {
movieListResults.innerHTML += "<li>" + movies[i] + "</li>"
};
My logic to add and remove titles in JS was correct but the logic to display the titles in HTML wasn't.
PS: FYI I'm a beginner!
Cheers
Is it possible to compare filenames for a set of files that are imported as Photoshop layers ?
I have a folder of 50 jpg images which I have used in a PSD file.
Now I want to check whether all the JPG files are used or not ?
Is it possible to do so ?
As I've said, Photoshop scripting can help you achieve this by using File Objects and basic javascript knowledge. I've modified my old script as you've desired and now it should work well with any nested groups and images.
I highly encourage you to learn scripting and ask questions here wherever you feels confused.
Save below code as 'Script.jsx' and run it from 'File > Scripts > Browse'
Update 2 : Now it saves log.txt file too as per you requested. P.S. Learn from this script and tweak it to your desired result.
// Managing Document
var docs = app.documents;
// Progress Bar
var win = new Window("window{text:'Progress',bounds:[100,100,400,150],bar:Progressbar{bounds:[20,20,280,31] , value:0,maxvalue:100}};");
// assigning activeDocument
if (docs.length != 0) {
var docRef = app.activeDocument;
// Defining the folder
alert("You will be prompted for the folder containing your images.\n" +
"Files will be selected with a '.png'/'.jpg/.jpeg' on the end in the same folder.");
var folder = Folder.selectDialog();
if (!folder) {
exit;
}
var photoFiles = folder.getFiles(/\.(jpg|jpeg|png)$/i);
var matchFiles = [];
var photoFilesName = [];
//Searching for used images
var increment = parseFloat(0);
var divider = parseFloat(100/photoFiles.length);
win.show();
for (var i = 0; i < photoFiles.length; i++) {
increment = increment + divider;
var indexPhotoName = removeExtension(photoFiles[i].displayName);
photoFilesName.push(indexPhotoName);
var doc = activeDocument;
var curLayer;
goThroughLayers(doc, indexPhotoName);
}
function goThroughLayers(parentLayer, targetName) {
for (var i = 0; i < parentLayer.layers.length; i++) {
curLayer = parentLayer.layers[i];
doc.activeLayer = curLayer;
if (curLayer.typename == 'LayerSet') {
goThroughLayers(curLayer, targetName)
} else {
if (curLayer.name == targetName) {
// if (curLayer.name.match(/[e]/ig)) {
matchFiles.push(targetName);
// }
} //end if
} //end else
} //end loop
} //end function
function arr_diff(a1, a2) {
var a = [],
diff = [];
for (var i = 0; i < a1.length; i++) {
a[a1[i]] = true;
}
for (var i = 0; i < a2.length; i++) {
if (a[a2[i]]) {
delete a[a2[i]];
} else {
a[a2[i]] = true;
}
}
for (var k in a) {
diff.push(k);
}
return diff;
}
function removeExtension(str) {
return str.split('.').slice(0, -1).join('.');
}
var missItems = arr_diff(matchFiles, photoFilesName);
if (missItems.length > 0) {
var missFolder = new Folder(photoFiles[0].path + '/Missed%20Files');
if(!missFolder.exists){
missFolder.create();
}
for (var y = 0; y < photoFiles.length; y++) {
var photoTrimName = removeExtension(photoFiles[y].displayName);
for( var x = 0; x < missItems.length ; x++){
if(photoTrimName == missItems[x]){
photoFiles[y].copy(new File(missFolder+'/'+photoFiles[y].displayName));
}
}
};
win.close();
alert("You've missed total " + missItems.length + " files. Press OK to open folder containing missing files. Log report is generated wherever PSD is saved.");
var FileStr = "";
for(var m=0; m<missItems.length; m++){
FileStr = FileStr + '\n' + (m+1) + '. ' + missItems[m];
}
var str = "Your missed files are : " + FileStr;
saveTxt(str);
missFolder.execute();
} else {
win.close();
saveTxt('All Photos are used');
alert('All Photos are used');
}
} else {
alert('Open atleast one document');
}
function saveTxt(txt)
{
var Name = "LogReport_" + app.activeDocument.name.replace(/\.[^\.]+$/, '');
var Ext = decodeURI(app.activeDocument.name).replace(/^.*\./,'');
if (Ext.toLowerCase() != 'psd')
return;
var Path = app.activeDocument.path;
var saveFile = File(Path + "/" + Name +".txt");
if(saveFile.exists)
saveFile.remove();
saveFile.encoding = "UTF8";
saveFile.open("e", "TEXT", "????");
saveFile.writeln(txt);
saveFile.close();
}
In Javascript, it is possible to get some information related to PSD file layers using PSD.js library
This is a sample code of what I'm trying to work on. I think it's probably a simple thing but the teachers on the front end course I'm in don't have an answer for me (either in the "here's the format to use" or "here's the proper way to do what you're trying here".)
var part1 = {
type = 1,
}
var part2 = {
type = 2,
}
var part3 = {
type = 3,
}
var partArray = [part1, part2, part3];
var carArray = [];
var truckArray = [];
for (i = 0; i < partArray.length; i++) {
if (part[i].type === 1 || part[i].type === 2) {
carArray.push(part[i]);
}
if (part[i].type === 3) {
truckArray.push(part[i]);
}
}
You are doing a few things incorrectly. First is how you create the properties in your part objects. Second is you are accessing a variable that doesn't exist part. I know you are trying to access part1, part2, part3. The thing is you already have those in your array, so the easiest is to access through there. Try this:
var part1 = {
type: 1
}
var part2 = {
type: 2
}
var part3 = {
type: 3
}
var partArray = [part1, part2, part3];
var carArray = [];
var truckArray = [];
for (var i = 0; i < partArray.length; i++){
if (partArray[i].type === 1 || partArray[i].type === 2){
carArray.push(partArray[i])
}
if (partArray[i].type === 3){
truckArray.push(partArray[i])
}
}
console.log(carArray)
console.log(truckArray)
You are using part instead of partArray
for (i=0; i < partArray.length; i++){
if (partArray[i].type === 1 || partArray[i].type === 2){
carArray.push(partArray[i])
}
if (partArray[i].type === 3){
truckArray.push(partArray[i])
}
}
I am trying to merger two json to one json. I don't want merge all keys, I added my code.
Code should be in javascript or node (underscore).
var json1 = [{user_id:1,friend_id:2,desc:'aaa'}, {user_id:3,friend_id:4,desc:'ccc'}, {user_id:1,friend_id:1,desc:'ccc'} , {user_id:1,friend_id:3,desc:'ccc'} ];
var json2 = [{reference_id:1,name:'A'},{reference_id:2,name:'B'},{reference_id:3,name:'C',age:30},{reference_id:4,name:'D'}];
Expecting Output:
output:
json1 = [{user_id:1,friend_id:2,desc:'aaa',user_name:'A',friend_name:'B'}, {user_id:3,friend_id:4,desc:'ccc',user_name:'C',friend_name:'D'}, {user_id:1,friend_id:1,desc:'ccc',user_name:'A',friend_name:'A'} , {user_id:1,friend_id:3,desc:'ccc',user_name:'A',friend_name:'C'} ];
Logic Js Code:
for (var i = 0; i < json1.length; i++) {
var user_id = json1[i].user_id;
var friend_id = json1[i].friend_id;
for (var j = 0; j < json2.length; j++) {
if (json2[j].reference_id == user_id) {
json1[i].user_name = json2[j].name;
}
if (json2[j].reference_id == friend_id) {
json1[i].friend_name = json2[j].name;
}
}
}
I attached my code in jsfiddle.Click Here
The same code should be convert into underscore.
You are repeating some effort here. Doesn't really matter if json2.length is small; but if it is large you will pay a penalty: you are looping over every element of json2 for every time you look at an element of json1. So instead, think of it this way:
var personMap = {};
json2.forEach(function(item) {
personMap[item.reference_id] = item.name;
});
json1.forEach(function(item) {
item.user_name = personMap[item.user_id];
item.friend_name = personMap[item.friend_id];
});
Your code in plain vanilla JS should work, except for "==" in the places where you've mistakenly put "=".
Replace these:
if (json2[j].reference_id = user_id) {
...
if (json2[j].reference_id = friend_id) {
...
with these:
if (json2[j].reference_id == user_id) {
...
if (json2[j].reference_id == friend_id) {
Try this is underscore:
_.map(json1, function(item){
var user_id = item.user_id;
var friend_id = item.friend_id;
_.map(json2, function(item2){
if (item2.reference_id == user_id) {
item.user_name = item2.name;
}
if (item2.reference_id == friend_id) {
item.friend_name = item2.name;
}
});
});
I would like to display a message on the page based on some value appearing in the URL. I have a known list of strings I'm looking for and the corresponding message. I cannot seem to get anywhere with the lookup / messaging. Could anyone pls kindly help? JavaScript only preferred, not jquery. Not that I the difference at this point ;)
Many thanks!
<div id="messagediv"></div>
Sample URLs to test:
<p>Campaign 1
<p>Campaign 2
<p>Campaign 3
<script>
(function () {
var params = window.location.search.substring(1).split('&'),
urlParams = {},
key, val;
for (var i = 01; i < params.length; i++) {
urlParams[params.split('=')[0]] = params.split('=')[1];
}
// querystring is ?utm_campaign=SpaCamp12458
// for instance, match URL query value SpaCamp12458 with the nums SpaComp key and show the corresponding text in the messagediv
var nums = {
defaultMessage: "Default Message",
"SpaComp": "Spas",
"PoolComp": "Recreation",
"BeachComp": "Outdoors"
}
for (var i in nums) {
if (nums.hasOwnProperty(i)) {
var found = false;
for (var j in urlParams) {
if (urlParams.hasOwnProperty(j)) {
if (urlParams[j].indexOf(nums[i]) === 0) {
document.getElementById("messagediv").innerHTML = nums[i];
found = true;
break;
}
}
}
if (!found) {
document.getElementById("messagediv").innerHTML = nums.defaultMessage;
}
}
}
})();
</script>