logo
Tags down

shadow

Remove singular element from an object's key array


By : DallasG
Date : October 18 2020, 06:10 PM
will help you I personally would refactor a bit your code, but I've worked a bit around it to fix some issues.
First of all, you shouldn't use delete for your scenario, because it will reset the item at the nth position of the array with the default value, which is undefined. Usually, for that kind of operations, since you deal with strings, you rather take a look at the first occurrence of your item in the array, take its index, and use splice (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice) to actually remove the item from the array.
code :
var toDoList = {}, archivedList = {};

function add(task, weekdayDue) {
 let capitalWeekday = weekdayDue.charAt(0).toUpperCase() + weekdayDue.slice(1);
 if (toDoList[capitalWeekday] === undefined) {
    let subArr = [];
    toDoList[capitalWeekday] = subArr.concat(task); 
 } else {
  toDoList[capitalWeekday].push(task);
 }
}

function remove(task, weekdayDue) {
  let capitalWeekday = weekdayDue.charAt(0).toUpperCase() + weekdayDue.slice(1);
  let taskIndex = toDoList[capitalWeekday].indexOf(task);
  toDoList[capitalWeekday].splice(taskIndex, 1);
  //delete toDoList[capitalWeekday][taskIndex];
  if (archivedList[capitalWeekday] === undefined) {
   let subArr = [];
   archivedList[capitalWeekday] = subArr.concat(task);
 } else {
   archivedList[capitalWeekday].push(task);
 }
};

add('test', 'monday');
add('wash car', 'monday');
remove('wash car', 'monday');

console.log(toDoList);
console.log(archivedList);


Share : facebook icon twitter icon

Deserialize XMLto array of objects, or singular object


By : user2079517
Date : March 29 2020, 07:55 AM
it should still fix some issue I ended up using XSLT to ensure the node(s) I was after weren't the root.
Basically I've a XSLT file containing:
code :
<xsl:template match="/">
    <rootNode>
        <xsl:apply-templates select="node()|@*"/>
    </rootNode>
</xsl:template>
//using reflection to look what the XmlType has been declared on this type
var typeAttributes = Attribute.GetCustomAttribute(typeof(T), typeof(XmlTypeAttribute));

//determine an xpath query to find this type of elements parent
string xPathtoTypeName = string.Format("//{0}/parent::node()", ((XmlTypeAttribute)typeAttributes).TypeName);

//use the above xpath query to find the parent node.
var parentNode = transformedDocument.SelectSingleNode(xPathtoTypeName);

//deserialize as before
XmlSerializer xmlSerializer = new XmlSerializer(typeof(T[]), new XmlRootAttribute(parentNode.Name));
XmlNodeReader nodeReader = new XmlNodeReader(parentNode);
results = xmlSerializer.Deserialize(nodeReader) as T[];

Remove element from array inside array of objects if present in another array of objects


By : CT5275
Date : March 29 2020, 07:55 AM
it helps some times Loop through arr and for each entry of arr, loop through lookup to compare and modify arr
code :
  for(let arrEntry of arr) {
    let id = arrEntry.id;
    let type1 = arrEntry.type1;
    let type2 = arrEntry.type2;

    for(let lookupEntry of lookup) {
      let title = lookupEntry.title;
      if(lookupEntry.id === id && type1.includes(title)) {
        type1.splice(type1.indexOf(title), 1);
      }
      if(lookupEntry.id === id && type2.includes(title)) {
        type2.splice(type2.indexOf(title), 1);
      }
    }
  }

  console.log(arr)

remove object property containing array inside array of objects if element in another array of objects


By : Sampada Nalawade
Date : March 29 2020, 07:55 AM
it fixes the issue For each object in the lookup check if the id matches in the arr array. If matches then get all the keys from that specific object in arr array using Object.keys.
pseudo code
code :
`{id: "12345",
    array1: ["Banana", "Apple"],
    array2: ["Orange", "Strawberry"]
  }['array0']` 
const arr = [{
    id: "12345",
    array1: ["Banana", "Apple"],
    array2: ["Orange", "Strawberry"]
  },
  {
    id: "12345",
    array0: ["Potato", "Tomato"]
  },
  {
    id: "54321",
    array0: ["Kiwi", "Apple"],
    array1: ["Potato", "Onion"]
  },
  {
    id: "54321",
    array2: ["Orange", "Tomato"],
    array0: ["Kiwi", "Banana"]
  },
  {
    id: "13579",
    array1: ["Banana", "Apple"],
    array2: ["Grapefruit", "Onion"]
  },
  {
    id: "13579",
    array1: ["Potato", "Banana"],
    array2: ["Orange", "Pepper"]
  }

]
const lookup = [{
    id: "12345",
    type: "Banana"
  },
  {
    id: "12345",
    type: "Kiwi"
  },
  {
    id: "12345",
    type: "Apple"
  },
  {
    id: "54321",
    type: "Strawberry"
  },
  {
    id: "54321",
    type: "Tomato"
  },
  {
    id: "54321",
    type: "Banana"
  },
  {
    id: "13579",
    type: "Tomato"
  },
  {
    id: "13579",
    type: "Grapefruit"
  }
]
let newArray = [];
lookup.forEach(function(item, index) {
  arr.forEach(function(arrId, index1) {
    if (item.id === arrId.id) {
      Object.keys(arrId).forEach(function(elem) {
        if (Array.isArray(arrId[elem]) && arrId[elem].indexOf(item.type) !== -1) {
          delete arr[index1][elem]
        }
      })
    }
  })
})
console.log(arr)

Returning singular child element with parent element in array


By : user3248173
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , Heres what I'm trying to do: , Problem statement simplified.
code :
var data = {
  users: {
    id: 1,
    username: "Admin",
    status: 1,
    created_at: "2019-07-23 21:49:56",
    updated_at: "2019-08-30 07:22:17",
    positions: [
      {
        id: 124,
        name: "Director",
        abbreviation: "Dir"
      },
      {
        id: 122,
        name: "Deputy Director",
        abbreviation: "DD"
      }
    ]
  },
  offices: [
    {
      id: 1,
      name: "Leadership Comittee",
      abbreviation: "LC",
      positions: [
        {
          id: 119,
          name: "Director",
          abbreviation: "Dir",
          pivot: {
            office: 1,
            position: 119,
            hierarchy: 1
          }
        },
        {
          id: 122,
          name: "Deputy Director",
          abbreviation: "DD",
          pivot: {
            office: 1,
            position: 122,
            hierarchy: 2
          }
        }
      ]
    },
    {
      id: 10,
      name: "Admin Comittee",
      abbreviation: "AC",
      positions: [
        {
          id: 124,
          name: "Director",
          abbreviation: "Dir",
          pivot: {
            office: 10,
            position: 124,
            hierarchy: 0
          }
        }
      ]
    }
  ],
  filter() {
    return this.users.positions.reduce((acc, userPosition) => {
        acc = [
          ...acc,
          ...this.offices
            .map(office => {
              return {
                ...office,
                positions: office.positions
                  .filter(
                    officePosition => officePosition.id === userPosition.id
                  )
                  .map(({ pivot, ...rest }) => rest)
              };
            })
            .filter(office => office.positions.length > 0)
        ];
      return acc;
    }, []);
  }
};

console.log(data.filter());

Compare an array of objects and an array of singular values


By : alidjator
Date : March 29 2020, 07:55 AM
wish of those help I have two arrays. One is filled with objects, the other is filled with values. See code below: , Here is a code snippet that might help.
code :
const data = [{id:1, name:'ben'},{id:2, name:'ben'}, {id:3, name:'ben'}, {id:4, name:'ben'}];
const ids = [1,3,4,5];

const newData = data.filter(chunk => ids.includes(chunk.id));
console.log("Filtered Data", newData);
Related Posts Related Posts :
  • How do I add a counter to show how many times a div element has been clicked?
  • Calling A function using vue.js components and properties
  • How to check type of "typeof" in JavaScript?
  • Recursive function to determine if number is even or odd by subtracting two from n until n = 0 or 1
  • How to fix:"Refused to run the JavaScript URL because it violates the following Content Security Policy..."
  • Can't access value inside of props object
  • How map and filter over array of objects?
  • How to invert d3 color ramps d3-scale-chromatic d3.interpolateViridis
  • Comparing two variables JavaScript
  • Google Pay & Web Payment Request API:
  • How to pass date as parameter in javascript function
  • why i have this error "Expected an assignment or function call and instead saw an expression no-unused-expressions&
  • calculate the full turns of a circle
  • Applying spread operator on object with getter
  • How do I hide a parent div when child div contains a certain text?
  • How to Stream Live Audio With Low Latency
  • React: How to close a modal from child opened from parent component
  • how to find tab close and clear local storage
  • Function returning undefined value, a bit confused
  • Assignment involving generic property of generic object fails to typecheck correctly within generic function
  • What is output for foo.x
  • How to fix lag issue over time in my Three.js game
  • async await promise.all map not resolving promises
  • Print an HTML document to PDF using JavaScript
  • Getting illegal invocation, after using $.ajax inside of $(doocument).keypress function
  • DebounceTime emits all the events which was captred during the time
  • Mongoose 5.x disallows passing a spread of operators
  • javascript onkeypress limit characters when pasting
  • How to fire an event only if specific-time has lapsed after scrolling has been stopped
  • How to filter an array of objects based on another array of objects?
  • Best way to switch between two colours with javascript?
  • Calling asynchronous function but returning result synchronously
  • Can't inject custom repository
  • How do I fix the Cordova error: Failed to fetch platform <<<<< HEAD?
  • Javascript: Store a global variable for a single page application
  • Node: Load/read the content of a page from external website(domain)
  • What is the difference between Object and object type
  • How to detect focusout on parent div not on child div in Angular4
  • How to end program after right answer?
  • How to use dot notation after +
  • Error from anonymous function: unexpected token <
  • Refresh a particular component in Angular
  • RegEx for validating three alphanumeric conditions
  • How to upload html file in the google and let it view by everyone?
  • Use Array.map on an 2-dimensional Array
  • Not sure whether I have syntax errors or errors with the code
  • How to fix process.nextTick is not a function with Calgolia places.js?
  • React Text Annotation
  • Is it possible to change the input type of an input element inside a <td> using <td> id with the use of java
  • Render functional component on variable change
  • Using Javascript to write a function which compares two trees and returns true if they are equal in structure and in val
  • How to save results from dynamic cascading drop down list?
  • How to pass arguments to function in functional component in React
  • Is there a way to view the contents of a predefined function like alert()?
  • object use own method in javascript
  • How do I replace NaN with 0 when doing division in javascript?
  • How to separate input field values in React?
  • How to link two JavaScript files together? NO HTML
  • Angular 7 - how to make initial input value visible for JSON?
  • How to get previous state value in reactjs
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk