Update the data from spliced array of object - javascript

So, I have splice the data and I want to update it's object from disabled = true to disabled = false .. I have looking for another answer and cant find one..
Any Advice is appreciated. Thank you
this is my dropdown
const newDrop = [
{ key: "1", label: "Monthly GMV", sublabel: "Max.1" },
{ key: "2", label: "AOV", sublabel: "Max.1" },
{ key: "3", label: "Monthly Order", sublabel: "Max.1" },
{ key: "4", label: "Last Purchase", sublabel: "Max.1" },
{ key: "5", label: "Has Purchase" },
{ key: "6", label: "Has Purchase Spesific Product" },
{ key: "7", label: "Located In", sublabel: "Max.1" },
];
selected function : when selected the dropdown, it will add new attribute disabled:true
newInput({ key }) {
const {
changeFormAttribute,
form: { selectedDrop, newDrop, data },
} = this.props;
itemIndex = newDrop.map((itm) => {
let x = itm.key === key;
return x && itm.key !== "6" && itm.key !== "5" ? { ...itm, disabled: true } : { ...itm };
});
changeFormAttribute({
newDrop: itemIndex,
});
}
delete function: this is onClick function, when clicked, it should splice the data, and check, if the spliced data have disabled === true change it to disabled:false . the spliced have working properly, but not change the attribute to disabled = false
deleteInput(index) {
const {
changeFormAttribute,
form: { selectedDrop },
} = this.props;
let selected = selectedDrop || [];
selected.splice(index, 1).map((e) => {return e.disabled === true ? false:true })
changeFormAttribute({ selectedDrop: selected });
}

Your splice function not returning the element. You may need to change it to
selected.splice(index, 1).map((e) => {
e.disabled === true ? false:true
return e;
})

Related

Add/Update a property in a deeply nested array of objects based on a given key and value

I've got a deeply nested array that looks like this:
const elements = [
{
type: "section",
id: "basic-section",
title: "Basic information",
children: [
{
type: "select",
label: "Entity type",
id: "entity-type",
options: [
{ value: "person", label: "Person" },
{ value: "company", label: "Company" },
{ value: "organisation", label: "Organisation" },
],
},
{
type: "group",
conditions: [
{ type: "isEqual", variable: "entity-type", value: ["person"] },
],
children: [
{ type: "text", label: "First name", id: "entity.firstName" },
{ type: "text", label: "Last name", id: "entity.lastName" },
{ type: "number", label: "Age", id: "entity.age" },
{
type: "select",
label: "Gender",
id: "entity.gender",
defaultValue: "female",
options: [
{ value: "male", label: "Male" },
{ value: "female", label: "Female" },
],
},
],
},
{
type: "group",
conditions: [
{
type: "isEqual",
variable: "entity-type",
value: ["company", "organisation"],
},
],
children: [
{ type: "text", label: "Name", id: "entity.name" },
{ type: "text", label: "Address", id: "entity.address" },
],
},
],
},
];
I'm trying to add and update a property based on a given key and value.
Example 1: Add an option to the options list of entity-type
Example 2: Update the defaultValue of entity.gender to male
My current steps to accomplish this actions are:
1) Find the element based on the id key and id value
const element = findObject(elements, 'id', 'entity-type');
function findObject(object, key, value) {
if(object.hasOwnProperty(key) && object[key] === value) {
return object;
}
for(let i = 0; i < Object.keys(object).length; i++){
if(typeof object[Object.keys(object)[i]] == "object") {
const o = findObject(object[Object.keys(object)[i]], key, value);
if(o !== null) return o;
}
}
return null;
}
2) Create new option
const newOption = { value: 'government', label: 'Government' };
3) Add the new option to the found element
const updatedElement = Object.assign({}, element, { options: [...element.options, newOption] });
4) Replace the old element with the updatedElement
const newElementsList = // Stuck
5) Update the state with the updatedElementsList
setElementsList(newElementsList);
I don't see how I can replace the original element with the updated one based on the key and value.
Can someone help me out?
This is not recommended, but you can keep track of parent. Once you find the element, update the parent data with update value. But you loose immutability.
A better approach would be found and update the same time.
const elements = [{"type":"section","id":"basic-section","title":"Basic information","children":[{"type":"select","label":"Entity type","id":"entity-type","options":[{"value":"person","label":"Person"},{"value":"company","label":"Company"},{"value":"organisation","label":"Organisation"}]},{"type":"group","conditions":[{"type":"isEqual","variable":"entity-type","value":["person"]}],"children":[{"type":"text","label":"First name","id":"entity.firstName"},{"type":"text","label":"Last name","id":"entity.lastName"},{"type":"number","label":"Age","id":"entity.age"},{"type":"select","label":"Gender","id":"entity.gender","defaultValue":"female","options":[{"value":"male","label":"Male"},{"value":"female","label":"Female"}]}]},{"type":"group","conditions":[{"type":"isEqual","variable":"entity-type","value":["company","organisation"]}],"children":[{"type":"text","label":"Name","id":"entity.name"},{"type":"text","label":"Address","id":"entity.address"}]}]}];
// console.log("%j", elements);
function findObject(element, key, value, { parent = null, index = -1 }) {
if (element.hasOwnProperty(key) && element[key] === value) {
return { element: element, parent, index };
}
let keys = Object.keys(element);
for (let i = 0; i < keys.length; i++) {
if (typeof element[keys[i]] == "object") {
const o = findObject(element[Object.keys(element)[i]], key, value, {
parent: element,
index: i,
});
if (o !== null) return o;
}
}
return { element: null };
}
const { element, parent, index } = findObject(
elements,
"id",
"entity-type",
{}
);
const newOption = { value: "government", label: "Government" };
const updatedElement = Object.assign({}, element, {
options: [...element.options, newOption],
});
if (parent && index !== -1) parent[index] = updatedElement;
console.log(JSON.stringify(elements, null, 4));

How to code 'ID of DOM method to using in recursion'?

I have a problem in 'getObjectById to using in recursion'. Executing the function getObject(data, '11') ---> undefined. I don't know why this happens: undefined.
In function getObject(data, '1'~'9') ---> I got the solved. But '11' ,'12', '13', '14' ---> undefined
For solving this problem, I have to use forEach, Array.prototype.apply, but I cannot solve it.
Using filter ---> TypeError: Cannot read property 'filter' of undefined
Using length ---> TypeError: Cannot read property 'length' of undefined
In first under line, I have got the problem to solve. In second under line, I wrote the code to solve this problem. As I think that I explain my logic to solving the problem. But, in test case, it is failed.
The solution to this problem is:
let output = getObjectById(TREE_DATA.items, '1'))
console.log(output) --> { "id": "1", "name": "johnny" }
--in first under line,
let TREE_DATA = {
items: [
{
id: "1",
name: "johnny"
},
{
id: "2",
name: "ingi",
children: [
{
id: "3",
name: "johnson"
},
{
id: "4",
name: "katy"
},
{
id: "5",
name: "steve",
children: [
{
id: "6",
name: "lisa"
},
{
id: "7",
name: "penny",
children: [
{
id: "8",
name: "john"
},
{
id: "9",
name: "hoyong"
}
]
},
{
id: "10"
}
]
},
{
id: "11"
},
{
id: "12"
}
]
},
{
id: "13"
},
{
id: "14"
}
]
};
--in second under line,
function getObject(json, id) {
let test = json.items;
let newA = [];
function getA(a, id) {
a.filter(function(e) {
console.log("this is : ", e);
if (e.id && e.id === id) {
return newA.push(e);
} else if (e.id !== id && e.children) {
return getA(e.children, id);
}
});
}
getA(test, id);
return newA[0];
}
Because your input data is a recursive structure, a program with a recursive structure will be the best match. In this case you have -
a list of nodes (TREE_DATA.items)
where each node (object) may contain a children property, which is also a list of nodes
This recursive relationship gives us a unique opportunity to learn about special kind of recursion where one function, A, calls function B, which in turn calls function A, which calls B, and so on... this is called mutual recursion.
We start with a function that takes just one of the input nodes, aptly named find1. It accepts a single node, destructured to children and o, and an id to search for, id -
const find1 = ({ children = [], ...o }, id = 0) =>
o.id == id // if the object's id matches the input id,
? o // match found! return the object
: findAll(children, id) // otherwise findAll of the children with the id
Next it's obvious we need to implement findAll. It accepts a list of nodes, destructured to first and more, and an id to search for, id -
const findAll = ([ first, ...more ], id = 0) =>
first === undefined // if the list is empty,
? undefined // there's nothing to search! return no match
: find1(first, id) // find1 the first item in the list using the id
|| findAll(more, id) // OR findAll on more using the same id
That's it! The functions almost writes themselves with no need for extraneous variables or steps. It behaves exactly like we expect -
console.log(findAll(TREE_DATA.items, 1))
// { id: "1", name: "johnny" }
console.log(findAll(TREE_DATA.items, 11))
// { id: "11" }
console.log(findAll(TREE_DATA.items, 99))
// undefined (no match found)
Verify the results in your own browser by running the snippet below -
const find1 = ({ children = [], ...o }, id = 0) =>
o.id == id
? o
: findAll(children, id)
const findAll = ([ first, ...more ], id = 0) =>
first === undefined
? undefined
: find1(first, id) || findAll(more, id)
const TREE_DATA =
{items:[{id:"1",name:"johnny"},{id:"2",name:"ingi",children:[{id:"3",name:"johnson"},{id:"4",name:"katy"},{id:"5",name:"steve",children:[{id:"6",name:"lisa"},{id:"7",name:"penny",children:[{id:"8",name:"john"},{id:"9",name:"hoyong"}]},{id:"10"}]},{id:"11"},{id:"12"}]},{id:"13"},{id:"14"}]}
console.log(findAll(TREE_DATA.items, 1))
// { id: "1", name: "johnny" }
console.log(findAll(TREE_DATA.items, 11))
// { id: "11" }
console.log(findAll(TREE_DATA.items, 99))
// undefined (no match found)
Is this what you are looking for?
let TREE_DATA = {
items: [
{
id: "1",
name: "johnny"
},
{
id: "2",
name: "ingi",
children: [
{
id: "3",
name: "johnson"
},
{
id: "4",
name: "katy"
},
{
id: "5",
name: "steve",
children: [
{
id: "6",
name: "lisa"
},
{
id: "7",
name: "penny",
children: [
{
id: "8",
name: "john"
},
{
id: "9",
name: "hoyong"
}
]
},
{
id: "10"
}
]
},
{
id: "11"
},
{
id: "12"
}
]
},
{
id: "13"
},
{
id: "14"
}
]
};
function getObject(json, id) {
let test = json.items;
let newA = [];
function getA(a, id) {
a &&
a.forEach(function(e) {
if (e.id === id) {
newA.push(e);
} else if (e.children) {
getA(e.children, id);
}
});
}
getA(test, id);
return newA[0];
}
function getObjectById(items, key) {
let ret = {};
for (let item of items) {
if (item.id === key) {
return item;
}
if (item.children) {
let innerRet = getObjectById(item.children, key);
if (Object.keys(innerRet).length) return innerRet;
}
}
return ret;
}
console.log("2", getObjectById(TREE_DATA.items, "2"));
console.log("3", getObjectById(TREE_DATA.items, "3"));
console.log("11", getObjectById(TREE_DATA.items, "11"));
console.log("12", getObjectById(TREE_DATA.items, "12"));
console.log("13", getObjectById(TREE_DATA.items, "13"));
console.log("2", getObject(TREE_DATA, "2"));
console.log("3", getObject(TREE_DATA, "3"));
console.log("11", getObject(TREE_DATA, "11"));
console.log("12", getObject(TREE_DATA, "12"));
console.log("13", getObject(TREE_DATA, "13"));
Edit: debugged and added your function as well.

Delete specific object with id

I have an array of objects, I need to delete a complete object based on the id
Input :
filters: [
{
key: "status",
label: "En attente",
value: "waiting",
id: 0
},
{
key: "dateDue[min]",
label: "15/12/2019",
value: "15/12/2019",
id: 1
},
{
key: "dateDue[max]",
label: "02/02/2020",
value: "02/02/2020",
id: 2
},
{
key: "bien",
values: [
{
label: "Studio Bordeaux",
value: 36,
id: 3
},
{
label: "Studio 2",
value: 34,
id: 184
}
]
},
{
key: "type",
values: [
{
type: "receipts",
label: "Loyer",
value: "loyer",
id: 4
},
{
type: "receipts",
label: "APL",
value: "apl",
id: 5
},
{
type: "spending",
label: "taxes",
value: "taxes",
id: 6
}
]
}
]
So I created a removeItem method with the id that must be deleted in parameters
removeItem method :
removeItem = (e, id) => {
const { filters } = this.state;
const remove = _.reject(filters, el => {
if (!_.isEmpty(el.values)) {
return el.values.find(o => o.id === id);
}
if (_.isEmpty(el.values)) {
return el.id === id;
}
});
this.setState({
filters: remove
});
};
I use lodash to make my job easier and more specifically _.reject
My issue is the following :
I manage to correctly delete the classic objects for example
{
key: "status",
label: "En attente",
value: "waiting",
id: 0
}
but my method however does not work for objects of the following form
{
key: "bien",
values: [
{
label: "Studio Bordeaux",
value: 36,
id: 3
},
{
label: "Studio 2",
value: 34,
id: 184
}
]
},
currently the whole object is deleted and not only the object in the values array according to its id
Here is my codesandbox!
thank you in advance for your help
EDIT
I found a solution with lodash (compact), I share my solution here :
removeIdFromCollection = id => {
const { filters } = this.state;
const newFilters = [];
_.map(filters, filter => {
if (filter.values) {
const valuesTmp = _.compact(
_.map(filter.values, value => {
if (value.id !== id) return value;
})
);
if (!_.isEmpty(valuesTmp)) {
return newFilters.push({
key: filter.key,
values: valuesTmp
});
}
}
if (filter.id && filter.id !== id) return newFilters.push(filter);
});
return newFilters;
};
removeItem = id => e =>
this.setState({
filters: this.removeIdFromCollection(id)
});
The values false, null, 0, "", undefined, and NaN are removed with lodash compact (_.compact(array))
Here is my updated codesandbox
You will need to filter the filters array and each values separately. Below is a recursive function which will remove items with the given id from the filters array and from the values property.
PS. This example is not using Lodash as I think it is not needed in this case.
removeIdFromCollection = (collection, id) => {
return collection.filter(datum => {
if (Array.isArray(datum.values)) {
datum.values = this.removeIdFromCollection(datum.values, id);
}
return datum.id !== id;
});
}
removeItem = (e, id) => {
const { filters } = this.state;
this.setState({
filters: this.removeIdFromCollection(filters, id),
});
};
The problem would be the structure of the object. You'll need to refactor for that inconvenient array out of nowhere for uniformity:
// Example
filters: [
...
{
key: "type",
values: [
{
type: "receipts",
label: "Loyer",
value: "loyer",
id: 4
},
...
]
...
}
// could be
filters: [
...
{
key: "type-receipts",
label: "Loyer",
value: "loyer",
id: 4
}
...
]
Repeat the pattern on all of it so you could just use the native array filter like this:
const newFilters = filters.filter(v => v.id !== id);
this.setState({
filters: newFilters,
});
I found a solution with lodash, I share it with you here :
removeIdFromCollection = id => {
const { filters } = this.state;
const newFilters = [];
_.map(filters, filter => {
if (filter.values) {
const valuesTmp = _.compact(
_.map(filter.values, value => {
if (value.id !== id) return value;
})
);
if (!_.isEmpty(valuesTmp)) {
return newFilters.push({
key: filter.key,
values: valuesTmp
});
}
}
if (filter.id && filter.id !== id) return newFilters.push(filter);
});
return newFilters;
};
removeItem = id => e =>
this.setState({
filters: this.removeIdFromCollection(id)
});
Here is my updated codesandbox

ReactJS object filter get undefined on componentDidMount

I use map to get data in componentDidMount:
componentDidMount() {
const DistrictOptions = Data.DistrictData.map((obj) => ({
key: obj.id,
text: obj.name,
value: obj.id,
cid: obj.cid
}));
console.log(DistrictOptions); // return data successfully
}
And it return data successfully, now I want to do a filter on this object, I treid:
const DistrictOptions = Data.DistrictData.filter(x => x.cid === 1).map((v, i) => {
return {
key: i,
value: v.id,
text: v.name
}
});
But this return empty array [] I also tried this:
const opt = DistrictOptions.find(x => x.cid === 1);
But this return undefined, confusing what happen here and what I done wrong. this is Data.DistrictData:
const Data = {
DistrictData: [{
"id": "1",
"name": "ss 1",
"cid": "1"
}, {
"id": "2",
"name": "ss 2",
"cid": "1"
}, {
"id": "3",
"name": "ss 3",
"cid": "1"
}
]
}
You can use == comparator for comparing cid as shown or use === operator and convert your cid to number:
Using ==
const DistrictOptions = Data.DistrictData.filter(x => x.cid == 1).map((v, i) => {
return {
key: i,
value: v.id,
text: v.name
}
});
Using ===
const DistrictOptions = Data.DistrictData.filter(x => Number(x.cid, 10) == 1).map((v, i) => {
return {
key: i,
value: v.id,
text: v.name
}
});
You can also use parseInt(x.cid,10) for a conversion to integer.

Tree json "menu" with nested items : check the "branch"

I have this JSON tree view that represents a menu :
var menus = [
{
label : "1",
items: [
{
label : "1.1"
},
{
label : "1.2",
items : [
{
label : "1.2.1"
},
{
label : "1.2.2"
}
]
},
{
label : "1.3"
},
]
},
{
label : "2"
}
]
I want to mutate this JSON by adding for each item a selected property. This property, a boolean, will be set to true if the label is the right one or this is the tricky part if the descendant is the right one.
For instance, if I'm looking for label 1.2, all labels 1 and 1.2 will be selected. So I will get this JSON :
var menus = [
{
label : "1",
selected : true,
items: [
{
label : "1.1"
selected : false
},
{
label : "1.2",
selected : true,
items : [
{
label : "1.2.1"
selected : false
},
{
label : "1.2.2",
selected : false
}
]
},
{
label : "1.3",
selected : false
},
]
},
{
label : "2",
selected : false
}
]
the selected : false is not necessary.
Lodash is OK for me;)!
Any suggestions?
edit : where I am ! --> https://codepen.io/anon/pen/XGoXjM?editors=0010
edit 2 : finding elements must not be based on the way I wrote the labels. The labels can be any string... Sorry...
Thanks
This solution uses a for loop to iterate recursively the menu items and their children. If an item is selected, it adds selected: true to the item and it's parents:
const selectMenuItems = menus => selectedLabel => {
const internal = arr => {
let selected = false
for(let i = 0; i < arr.length; i++) {
const item = arr[i]
const childrenSelected = !!item.items && internal(item.items)
item.selected = childrenSelected || item.label === selectedLabel
selected = selected || item.selected
}
return selected
}
internal(menus)
return menus
}
const menus = [{"label":"1","items":[{"label":"1.1"},{"label":"1.2","items":[{"label":"1.2.1"},{"label":"1.2.2"}]},{"label":"1.3"}]},{"label":"2"}]
const menuSelector = selectMenuItems(menus)
const result = menuSelector('1.2')
console.log(result)
.as-console-wrapper { top: 0; max-height: 100% !important; }
I would simply check labels this way:
var menus = [{
label: "1",
items: [{
label: "1.1"
},
{
label: "1.2",
items: [{
label: "1.2.1"
},
{
label: "1.2.2"
}
]
},
{
label: "1.3"
},
]
},
{
label: "2"
}
];
var checkSelected = function(items, search) {
for (var key in items) {
items[key].selected = search.startsWith(items[key].label) && items[key].label.length<=search.length;
if (items[key].items) {
checkSelected(items[key].items, search);
};
};
};
var test = "1.2";
checkSelected(menus, test);
console.log(menus);
Also on JSFiddle.
The startsWith() method determines whether a string begins with the
characters of a specified string, returning true or false as
appropriate.
quoted from here
You can use some recursive approach to implement this.
let str = '1.2.1';
function checkItem(arr, strArr) {
// iterate over the array
arr.forEach((obj) => {
// set selected property based on matching every digit in label in same order
// if digits would be single then you can use startsWith and no need to split string
obj.selected = obj.label.split('.').every((it, i) => it === strArr[i]);
// if nested item is there then call recursively
obj.items && checkItem(obj.items, strArr);
});
return arr;
}
checkItem(menus, str.split('.'));
var menus = [{
label: "1",
items: [{
label: "1.1"
},
{
label: "1.2",
items: [{
label: "1.2.1"
},
{
label: "1.2.2"
}
]
},
{
label: "1.3"
},
]
},
{
label: "2"
}
];
let str = '1.2.1';
function checkItem(arr, strArr) {
arr.forEach((obj) => {
obj.selected = obj.label.split('.').every((it, i) => it === strArr[i]);
obj.items && checkItem(obj.items, strArr);
});
return arr;
}
checkItem(menus, str.split('.'));
console.log(menus);
UPADATE : Since you want to update selected property completely independent of label you can do something like follows. I assume you want to
update based on position in the array.
let str = '1.2.1';
function checkItem(arr, prefixArray, strArr) {
// iterate over the array
arr.forEach((obj, i) => {
// generate new prefix array for checking
let pa = [...prefixArray, i + 1];
// compare prefix array with the string array to check matches
obj.selected = pa.every((it, i) => it == strArr[i]);
// if items defined do it recursively
obj.items && checkItem(obj.items, pa, strArr);
});
return arr;
}
checkItem(menus,[], str.split('.'));
var menus = [{
label: "1",
items: [{
label: "1.1"
},
{
label: "1.2",
items: [{
label: "1.2.1"
},
{
label: "1.2.2"
}
]
},
{
label: "1.3"
},
]
},
{
label: "2"
}
];
let str = '1.2.1';
function checkItem(arr, prefixArray, strArr) {
arr.forEach((obj, i) => {
let pa = [...prefixArray, i + 1];
obj.selected = pa.every((it, i) => it == strArr[i]);
obj.items && checkItem(obj.items, pa, strArr);
});
return arr;
}
checkItem(menus,[], str.split('.'));
console.log(menus);

Categories

Resources