I have 2 arrays.
const finalArr = []
const arr = ["abc","def"]
const arr2 = [
{ name: "abc", refresh: false },
{ name: "efd", refresh: false },
{ name: "def", refresh: false }
]
Now I am trying to update the value of refresh to true from arr2 for the name matches from arr, It returns duplicate values:
Here is my code:
arr2.map(obj => {
arr.map(name => {
if (obj.name === name){
finalArr.push({ ...obj, refresh: true })
} else{
finalArr.push({ ...obj, refresh: false })
}
})
Can anybody tell me what is wrong with it?
This is simple:
const finalArray = arr2.map(obj => {
return { ...obj, refresh: arr.includes(obj.name) };
}
Related
I got Logitech MX Anywhere 3 mouse and I am using on Ubuntu. I have installed the drivers and I am using logid to configure it. However I cannot manage to adjust the scrolling speed using the logid.cfg file. Any ideas on how to do that?
// Logiops (Linux driver) configuration for Logitech MX Master 3.
// Includes gestures, smartshift, DPI.
// Tested on logid v0.2.3 - GNOME 3.38.4 on Zorin OS 16 Pro
// What's working:
// 1. Window snapping using Gesture button (Thumb)
// 2. Forward Back Buttons
// 3. Top button (Ratchet-Free wheel)
// What's not working:
// 1. Thumb scroll (H-scroll)
// 2. Scroll button
// File location: /etc/logid.cfg
devices: ({
name: "MX Anywhere 3";
smartshift: {
on: true;
threshold: 5;
};
hiresscroll: {
hires: true;
invert: true;
target: false;
};
dpi: 1200; // max=4000
buttons: (
// Forward button
{
cid: 0x56;
action = {
type: "Gestures";
gestures: (
{
direction: "None";
mode: "OnRelease";
action = {
type: "Keypress";
keys: [ "KEY_FORWARD" ];
}
},
{
direction: "Up";
mode: "OnRelease";
action = {
type: "Keypress";
keys: [ "KEY_PLAYPAUSE" ];
}
},
{
direction: "Down";
mode: "OnRelease";
action = {
type: "Keypress";
keys: [ "KEY_LEFTMETA" ];
}
},
{
direction: "Right";
mode: "OnRelease";
action = {
type: "Keypress";
keys: [ "KEY_NEXTSONG" ];
}
},
{
direction: "Left";
mode: "OnRelease";
action = {
type: "Keypress";
keys: [ "KEY_PREVIOUSSONG" ];
}
}
);
};
},
// Back button
{
cid: 0x53;
action = {
type: "Gestures";
gestures: (
{
direction: "None";
mode: "OnRelease";
action = {
type: "Keypress";
keys: [ "KEY_BACK" ];
}
}
);
};
},
// Gesture button (hold and move)
{
cid: 0xc3;
action = {
type: "Gestures";
gestures: (
{
direction: "None";
mode: "OnRelease";
action = {
type: "Keypress";
keys: [ "KEY_LEFTMETA" ]; // open activities overview
}
},
{
direction: "Right";
mode: "OnRelease";
action = {
type: "Keypress";
keys: [ "KEY_LEFTMETA", "KEY_RIGHT" ]; // snap window to right
}
},
{
direction: "Left";
mode: "OnRelease";
action = {
type: "Keypress";
keys: [ "KEY_LEFTMETA", "KEY_LEFT" ];
}
},
{
direction: "Up";
mode: "onRelease";
action = {
type: "Keypress";
keys: [ "KEY_LEFTMETA", "KEY_UP" ]; // maximize window
}
},
{
direction: "Down";
mode: "OnRelease";
action = {
type: "Keypress";
keys: [ "KEY_LEFTMETA", "KEY_DOWN" ]; // minimize window
}
}
);
};
},
// Top button
{
cid: 0xc4;
action = {
type: "Gestures";
gestures: (
{
direction: "None";
mode: "OnRelease";
action = {
type: "ToggleSmartShift";
}
},
{
direction: "Up";
mode: "OnRelease";
action = {
type: "ChangeDPI";
inc: 1000,
}
},
{
direction: "Down";
mode: "OnRelease";
action = {
type: "ChangeDPI";
inc: -1000,
}
}
);
};
}
);
});
I want to compare the two models mainArray and resultArray. If category_name and sub_category_name are found to be same, the mainArray is_selected is to be changed to true. How can I achieve this? They both are models.
var mainArray : [Item] = [
{
"category_name": "Wellness",
"sub_category": [
{
"sub_category_name": "Health",
"is_selected": false
},
{
"sub_category_name": "Psychedelics",
"is_selected": false
},
{
"sub_category_name": "Meditation",
"is_selected": false
},
{
"sub_category_name": "Nutrition",
"is_selected": false
},
{
"sub_category_name": "Outdoors",
"is_selected": false
},
{
"sub_category_name": "Medicine",
"is_selected": false
},
{
"sub_category_name": "Mindfulness",
"is_selected": false
},
{
"sub_category_name": "Fitness",
"is_selected": false
},
{
"sub_category_name": "Weights",
"is_selected": false
},
{
"sub_category_name": "Veganism",
"is_selected": false
}
]
},
{
"category_name": "Hustle",
"sub_category": [
{
"sub_category_name": "Tik Tok",
"is_selected": false
},
{
"sub_category_name": "ClubHouse",
"is_selected": false
},
{
"sub_category_name": "Stocks",
"is_selected": false
},
{
"sub_category_name": "Networking",
"is_selected": false
},
{
"sub_category_name": "Small business",
"is_selected": false
},
{
"sub_category_name": "Instagram",
"is_selected": false
},
{
"sub_category_name": "Enterpreneurship",
"is_selected": false
},
{
"sub_category_name": "Real Estate",
"is_selected": false
},
{
"sub_category_name": "Pitch practice",
"is_selected": false
}
]
}
]
var resultArray : [Item] = [
{
"category_name": "Wellness",
"sub_category": [
{
"sub_category_name": "Psychedelics"
},
{
"sub_category_name": "Fitness"
}
]
},
{
"category_name": "Hustle",
"sub_category": [
{
"sub_category_name": "ClubHouse"
}
]
}
]
This is the Item Model
// MARK: - Item
class Item: Codable {
let category_name: String
let sub_category: [SubCategory]
enum CodingKeys: String, CodingKey {
case category_name = "category_name"
case sub_category = "sub_category"
}
init(categoryName: String, subCategory: [SubCategory]) {
self.category_name = categoryName
self.sub_category = subCategory
}
}
First of all
var mainArray : [Item] = [{
makes no sense because the data is a JSON string rather than an array of Item.
Second of all it's a bit tricky to update an array in place because you might have to deal with value semantics.
This suggestion works even with structs. I changed the names to more Swift-compliant names
let main = """
[
{
"category_name": "Wellness",
"sub_category": [ ...
let result = """
[
{
"category_name": "Wellness",
"sub_category": [ ...
struct Category: Codable {
let name: String
var subCategories: [SubCategory]
private enum CodingKeys: String, CodingKey {
case name = "category_name"
case subCategories = "sub_category"
}
}
struct SubCategory: Codable {
let name: String
var isSelected = false
private enum CodingKeys: String, CodingKey { case name = "sub_category_name" }
}
func select(main: inout [Category], from result: [Category]) {
result.forEach { category in
guard let mainCategoryIndex = main.firstIndex(where: {$0.name == category.name}) else { return }
for subCategory in category.subCategories {
guard let subCategoryIndex = main[mainCategoryIndex].subCategories.firstIndex(where: {$0.name == subCategory.name}) else { return }
main[mainCategoryIndex].subCategories[subCategoryIndex].isSelected = true
}
}
}
do {
var main = try JSONDecoder().decode([Category].self, from: Data(main.utf8))
let result = try JSONDecoder().decode([Category].self, from: Data(result.utf8))
select(main: &main, from: result)
print(main)
} catch {
print(error)
}
I'm trying to filter the data from the sub_category array and show on the data in which isSelected is true. I have tried using flatmap and filter but am still not able to achieve the desired output. Please help.
{
"data": [
{
"category_name": "Social Sites",
"sub_category": [
{
"sub_category_name": "Instagram",
"isSelected" : true
},
{
"sub_category_name": "Facebook",
"isSelected" : true
},
{
"sub_category_name": "Twitter",
"isSelected" : false
}
]
},
{
"category_name": "",
"sub_category": [
{
"sub_category_name": "State",
"isSelected" : false
}
]
},
{
"category_name": "Sports",
"sub_category": [
{
"sub_category_name": "Cricket",
"isSelected" : true
},
{
"sub_category_name": "Hockey",
"isSelected" : false
}
]
}
]
}
Desired Output is only for isSelected = true
{
"data": [
{
"category_name": "Social Sites",
"sub_category": [
{
"sub_category_name": "Instagram",
"isSelected" : true
},
{
"sub_category_name": "Facebook",
"isSelected" : true
}
]
},
{
"category_name": "Sports",
"sub_category": [
{
"sub_category_name": "Cricket",
"isSelected" : true
}
]
}
]
}
I have tried using flatMap and filter, the following is my code.(But not able to achieve the desired output.)
let filtered = self.itemModelArray.flatMap { item in
item.subCategory!.filter({ (subCat) -> Bool in
subCat.isSelected == true
})
}
The above code gives me the array of subCategory,that is not what I want.
The following is my model
// MARK: - Item
struct Item: Codable {
let category_name: String
var sub_category: [SubCategory]
init(cat:String,subCat:[SubCategory]){
self.category_name = cat
self.sub_category = subCat
}
}
// MARK: - SubCategory
struct SubCategory: Codable {
let sub_category_name: String
var isSelected : Bool = false
init(subCat:String){
self.sub_category_name = subCat
}
Something like this would filter out both empty categories & non-selected sub-categories:
import Foundation
let json: String = <the json in the question, omited for brevity>
struct Model: Codable {
let data: [Category]
struct Category: Codable {
let category_name: String
let sub_category: [SubCategory]
}
struct SubCategory: Codable {
let sub_category_name: String
let isSelected: Bool
}
}
// Note: Handle any errors properly in production code
let model = try? JSONDecoder().decode(Model.self, from: Data(json.utf8))
var output: [Model.Category] = []
for category in model?.data ?? [] {
let selectedSubCategories = category.sub_category.filter(\.isSelected)
if !selectedSubCategories.isEmpty {
output.append(Model.Category(category_name: category.category_name, sub_category: selectedSubCategories))
}
}
which produces an array of 2 categories:
dump(output)
▿ 2 elements
▿ main.Model.Category
- category_name: "Social Sites"
▿ sub_category: 2 elements
▿ main.Model.SubCategory
- sub_category_name: "Instagram"
- isSelected: true
▿ main.Model.SubCategory
- sub_category_name: "Facebook"
- isSelected: true
▿ main.Model.Category
- category_name: "Sports"
▿ sub_category: 1 element
▿ main.Model.SubCategory
- sub_category_name: "Cricket"
- isSelected: true
I need to change values in array of object
Array of selected sports which is received from API
Update API Response
arrSelectedID = [["slug": cricket,
"id": 1,
"banner_image": https://_1558964043.jpg,
"name": Cricket,
"icons": {
black = "https://sport_icon_cricket_black.png";
green = "https://sport_icon_cricket_green.png";
grey = "https://sport_icon_cricket_gray.png";
white = "https://sport_icon_cricket_white.png";
}],
["slug": soccer,
"banner_image": https://1558964051.jpg
"icons": {
black = "https://sport_icon_soccer_black.png";
green = "https://sport_icon_soccer_green.png";
grey = "https://sport_icon_soccer_gray.png";
white = "https://sport_icon_soccer_white.png";
},
"id": 2,
"name": Soccer]]
My Array
struct ObjSportsList:Codable {
var id:Int
var name:String
var slug:String
var selected:Bool?
var icons:ObjSportsIcon
}
struct ObjSportsIcon:Codable {
var green:String
var grey:String
var white:String
var black:String
}
var arrSports:[ObjSportsList] = [] // Array which is custom object
Below response is printed my custom object "ObjSportsList"
arrSports = (id: 1,
name: "Cricket",
slug: "cricket",
selected: nil,
),
(id: 2,
name: "Soccer",
slug: "soccer",
selected: nil,
),
(id: 3,
name: "Baseball",
slug: "baseball",
selected: nil,
),
I want to change "selected" values = true which is get id from API array in "data" Example : [1,3] only change 1st and 3rd selected values == true
I try to work with below code but array not updated
for (index, var sports) in self.arrSports.enumerated() {
for selectedSports in arrSelectedID {
if selectedSports["id"] as! Int == sports.id {
sports.selected = true
}
}
Please refer below code to replace the specific value in Array of object
let aryIDS = [1,3]
for (index, sport) in arrSports.enumerated(){
if aryIDS.contains(sport.id) {
arrSports[index].selected = true
}
}
print(arrSports) //Received updated array
I fix the issue with my own code, Please check this code
for (index, sports) in self.arrSports.enumerated() {
for selectedSports in arrSelectedID {
if selectedSports["id"] as! Int == sports.id {
self.arrSports[index].selected = true
}
}
}
I'm using jsTree plugin in my ASP.NET MVC application and have a strange issue. I've attached contextMenu plugin, but its items have a strange empty space on the left, like in the image below:
My code is followed:
$(function () {
$("#competence-areas-tree").jstree({
core: {
data: {
cache: false,
url: '#Url.Action("GetTreeData", "CompetenceArea")'
},
multiple: false
},
types: {
competenceArea: {
icon: "#Url.Stylesheet("/jstree-3.0.0b/competenceArea.png")"
}
},
contextmenu: {
items: function ($node) {
return {
createItem: {
separator_before: false,
separator_after: false,
label: "Создать",
submenu: {
create: {
separator_before: false,
separator_after: false,
label: "Создать на текущем уровне",
action: function() {
Create($node.parent);
}
},
createChild: {
separator_before: false,
separator_after: false,
label: "Создать потомка",
action: function() {
Create($node.id);
}
}
}
},
editItem: {
separator_before: false,
separator_after: false,
label: "Редактировать",
action: function() {
Edit($node.id);
}
},
deleteItem: {
separator_before: false,
separator_after: false,
label: "Удалить",
action: function() {
Delete($node.id);
}
},
detailGraphItem: {
separator_before: false,
separator_after: false,
label: "Перейти к графу",
action: function() {
DetailGraph($node.id);
}
}
}
}
},
plugins: ["types", "contextmenu", "themes"]
}).on("changed.jstree", function(e, data) {
if (data.action === "select_node") {
OnSelectingNode(data.node.original.id);
}
});
});
Thank you!
Hmm I made a jsfiddle for the context menu you have provided but there isn't anything wrong with it. There is always a default space to the left with the context menu in the jstree but not to the extent that you're having. Here is the jsfiddle to see if that can help:
http://jsfiddle.net/3q9Ma/529/
$(function () {
var data = [
{ "id" : "ajson1", "parent" : "#", "text" : "Simple root node" },
{ "id" : "ajson2", "parent" : "#", "text" : "Root node 2" },
{ "id" : "ajson3", "parent" : "ajson2", "text" : "Child 1" },
{ "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2" },
];
$("#jstree").jstree({
"core" : {
"check_callback" : true,
"data": data
},
"plugins" : [ "contextmenu", "dnd"],
contextmenu: {
items: function ($node) {
return {
createItem: {
separator_before: false,
separator_after: false,
label: "Создать",
submenu: {
create: {
separator_before: false,
separator_after: false,
label: "Создать на текущем уровне",
action: function() {
Create($node.parent);
}
},
createChild: {
separator_before: false,
separator_after: false,
label: "Создать потомка",
action: function() {
Create($node.id);
}
}
}
},
editItem: {
separator_before: false,
separator_after: false,
label: "Редактировать",
action: function() {
Edit($node.id);
}
},
deleteItem: {
separator_before: false,
separator_after: false,
label: "Удалить",
action: function() {
Delete($node.id);
}
},
detailGraphItem: {
separator_before: false,
separator_after: false,
label: "Перейти к графу",
action: function() {
DetailGraph($node.id);
}
}
}
}
}
}).on('create_node.jstree', function(e, data) {
console.log('saved');
});
$("#sam").on("click",function() {
$('#jstree').jstree().create_node('#' , { "id" : "ajson5", "text" : "newly added" }, "last", function(){
alert("done");
});
});
});