I have an array like below
[{
"IM_Id":1,
"IM_Name":"Hello",
"ItemNumber":2001,
"FE_Id":2,
"FE_Name":"Wall",
"FE_Code":"XYZ",
"FC_Id":[2,3],
"FC_Name":["ABC","PQR"],
"FC_Value":[9,7],
"OC_Id":6,
"OC_Name":"Rai",
"OC_Price":"$30",
"CH_Id":4,
"CH_Name":"Sen",
"CH_Code":"LMN",
"CO_Id":[5,9],
"CO_Name":["xyz","pqr"],
"CO_Value":["qqq","LMN"]
},
{
"IM_Id":2,
"IM_Name":"World",
"ItemNumber":2002,
"FE_Id":3,
"FE_Name":"WallMart",
"FE_Code":"009F",
"FC_Id":[4,5],
"FC_Name":["ABCD","PQRS"],
"FC_Value":[4,2],
"OC_Id":7,
"OC_Name":"Raj",
"OC_Price":"$60",
"CH_Id":7,
"CH_Name":"Ken",
"CH_Code":"IJK"
}]
You can see FC_Id,FC_Name,FC_Value have 2 elements and these 3 parameters are actually related.
Similarly all parameters prepended with CO have same pattern.
I want my resulting array should consider every element of array one by one.
So for the first element of array, it should consider one by one elements of FC_Id,FC_Name,FC_Value,CO_Id,CO_Name and CO_Value.
It should actually consider all the elements of subarrays and main array both.
And hence my result should be something as below
[{
"IM_Id":1,
"IM_Name":"Hello",
"ItemNumber":2001,
"FE_Id":2,
"FE_Name":"Wall",
"FE_Code":"XYZ",
"FC_Id":2, //Here it took the first element
"FC_Name":"ABC", // //Here it took the first element
"FC_Value":9, ////Here it took the first element
"OC_Id":6,
"OC_Name":"Rai",
"OC_Price":"$30",
"CH_Id":4,
"CH_Name":"Sen",
"CH_Code":"LMN",
"CO_Id":5,
"CO_Name":"xyz",
"CO_Value":"qqq"
},
{
"IM_Id":1,
"IM_Name":"Hello",
"ItemNumber":2001,
"FE_Id":2,
"FE_Name":"Wall",
"FE_Code":"XYZ",
"FC_Id":3, //Here it took the second element
"FC_Name":"PQR", //Here it took the second element
"FC_Value":7,//Here it took the second element
"OC_Id":6,
"OC_Name":"Rai",
"OC_Price":"$30",
"CH_Id":4,
"CH_Name":"Sen",
"CH_Code":"LMN",
"CO_Id":9,
"CO_Name":"pqr",
"CO_Value":"LMN"
},
{
"IM_Id":2,
"IM_Name":"World",
"ItemNumber":2002,
"FE_Id":3,
"FE_Name":"WallMart",
"FE_Code":"009F",
"FC_Id":4,
"FC_Name":"ABCD",
"FC_Value":4,
"OC_Id":7,
"OC_Name":"Raj",
"OC_Price":"$60",
"CH_Id":7,
"CH_Name":"Ken",
"CH_Code":"IJK",
"CO_Id":"-",
"CO_Name":"-",
"CO_Value":"-"
},
{
"IM_Id":2,
"IM_Name":"World",
"ItemNumber":2002,
"FE_Id":3,
"FE_Name":"WallMart",
"FE_Code":"009F",
"FC_Id":5,
"FC_Name":"PQRS",
"FC_Value":2,
"OC_Id":7,
"OC_Name":"Raj",
"OC_Price":"$60",
"CH_Id":7,
"CH_Name":"Ken",
"CH_Code":"IJK",
"CO_Id":"-", // as there's no element here we are inputting a '-'
"CO_Name":"-",
"CO_Value":"-"
}
]
Also, note that as there are no CO_ values for Item Number 2002 am putting a "-".
There will be more more other parameters in the array too I need some dynamic logic to create the resulting array
Something like this:
For each element of the data
Find at least one list of IDs between FC and CO (or construct a one-element list if no such list is found)
Iterate its length, and replace the relevant entries with subentries
Flatten the result
let data = [{"IM_Id":1,"IM_Name":"Hello","ItemNumber":2001,"FE_Id":2,"FE_Name":"Wall","FE_Code":"XYZ","FC_Id":[2,3],"FC_Name":["ABC","PQR"],"FC_Value":[9,7],"OC_Id":6,"OC_Name":"Rai","OC_Price":"$30","CH_Id":4,"CH_Name":"Sen","CH_Code":"LMN","CO_Id":[5,9],"CO_Name":["xyz","pqr"],"CO_Value":["qqq","LMN"]},{"IM_Id":2,"IM_Name":"World","ItemNumber":2002,"FE_Id":3,"FE_Name":"WallMart","FE_Code":"009F","FC_Id":[4,5],"FC_Name":["ABCD","PQRS"],"FC_Value":[4,2],"OC_Id":7,"OC_Name":"Raj","OC_Price":"$60","CH_Id":7,"CH_Name":"Ken","CH_Code":"IJK"}];
let result = [].concat(...data.map(r =>
(Array.isArray(r.FC_Id) ? r.FC_Id :
Array.isArray(r.CO_Id) ? r.CO_Id :
[0]
).map((_, i) =>
Object.assign({}, r, {
FC_Id: r.FC_Id ? r.FC_Id[i] : "-",
FC_Name: r.FC_Name ? r.FC_Name[i] : "-",
FC_Value: r.FC_Value ? r.FC_Value[i] : "-",
CO_Id: r.CO_Id ? r.CO_Id[i] : "-",
CO_Name: r.CO_Name ? r.CO_Name[i] : "-",
CO_Value: r.CO_Value ? r.CO_Value[i] : "-",
})
)
));
console.log(result);
Here is a snippet to achieve this. If you need to handle more properties with values as arrays, simple add them to props array :
let props = ["FC_Id", "FC_Name", "FC_Value", "CO_Id", "CO_Name", "CO_Value"]
Sample snippet
let arr = [{
"IM_Id": 1,
"IM_Name": "Hello",
"ItemNumber": 2001,
"FE_Id": 2,
"FE_Name": "Wall",
"FE_Code": "XYZ",
"FC_Id": [2, 3],
"FC_Name": ["ABC", "PQR"],
"FC_Value": [9, 7],
"OC_Id": 6,
"OC_Name": "Rai",
"OC_Price": "$30",
"CH_Id": 4,
"CH_Name": "Sen",
"CH_Code": "LMN",
"CO_Id": [5, 9],
"CO_Name": ["xyz", "pqr"],
"CO_Value": ["qqq", "LMN"]
},
{
"IM_Id": 2,
"IM_Name": "World",
"ItemNumber": 2002,
"FE_Id": 3,
"FE_Name": "WallMart",
"FE_Code": "009F",
"FC_Id": [4, 5],
"FC_Name": ["ABCD", "PQRS"],
"FC_Value": [4, 2],
"OC_Id": 7,
"OC_Name": "Raj",
"OC_Price": "$60",
"CH_Id": 7,
"CH_Name": "Ken",
"CH_Code": "IJK"
}
]
function convertArray() {
let result = [];
let props = ["FC_Id", "FC_Name", "FC_Value", "CO_Id", "CO_Name", "CO_Value"]
arr.forEach(function(obj) {
// Assume `FC_Id` array length is the reference array length
obj["FC_Id"].forEach(function(id, $index) {
// Create a clone of original object, so that we only have to override `props` defined above
let objClone = JSON.parse(JSON.stringify(obj));
// Override each prop value
props.forEach(function(prop) {
// Ensure original object property is an array with enough elements
if (obj[prop] instanceof Array && obj[prop].length > $index) {
objClone[prop] = obj[prop][$index];
}
else {
// else simply use an hyphen as value
objClone[prop] = "-";
}
});
// Push clone to result
result.push(objClone);
});
});
return result;
}
let newArray = convertArray();
console.log(JSON.stringify(newArray, null, 2));
From where are you creating this array . If you create this array in JavaScript or from webservice class. Then we could tell you the generic class for it. And a small method to convert the class element in your desire output array.
Let me answer in JavaScript code.
// I am creating a array object manual you could get it from source or from server json.
var Arr=[];
var obj={};
Obj.Name="fc_name";
obj.Value="12";
Arr.push(obj);
var obj={};
Obj.Name="fc_value";
obj.Value="dieje";
Arr.push(obj);
Similarly push all the elements in the array.
Then you will have a array of object with name value.
Arr=[
{"Name":"fc_value",
"Value":""dieje"
},
...
});
Now use below function to convert this array of object into your desire array.
function Convert(arr)
{
var array=[];
var obj={};
Arr.forEach(value)
{
obj[value.Name]=value.Value;
}
array.push(obj);//this is for single object you could apply loop to get the multiple value in array.
}
Related
I have an object that has multiple keys and each of these keys has an array storing multiple elements. I want to be able to remove a specified element from the key's array.
I have tried using the delete keyword as well as the filter method, but I have been unsuccessful. I'm a total newbie to JS so I appreciate any assistance. Also, I want to do this using ONLY JavaScript, no libraries.
Here is the code where I am creating my object:
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);
}
}
and here is the code as I have it now. Clearly it is not producing the correct result:
function remove(task, weekdayDue) {
let capitalWeekday = weekdayDue.charAt(0).toUpperCase() +
weekdayDue.slice(1);
delete toDoList.capitalWeekday[task]
//the below code is working; i want to send this to another
array
if (archivedList[capitalWeekday] === undefined) {
let subArr = [];
archivedList[capitalWeekday] = subArr.concat(task);
} else {
archivedList[capitalWeekday].push(task);
}
};
add('laundry', 'monday');
add('wash car', 'monday');
add ('vacuum', 'tuesday');
add('run errands', 'wednesday');
add('grocery shopping', 'wednesday');
// the output is: { Monday: [ 'laundry', 'wash car' ],
Tuesday: [ 'vacuum' ],
Wednesday: [ 'run errands', 'grocery shopping' ] }
Then let's say I want to remove 'wash car' from Monday I was trying:
remove('wash car', 'monday');
console.log(toDoList)
// The output is an empty object {}
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.
In this way, you end up with a clean array without invalid items in it.
Below is the working code (with the mentioned fixes) that does what you asked. As a side note, I would suggest you to avoid working with strings for such purposes, but I would rather tackle objects with unique ids, so that it's significantly easier to keep track of them between arrays and objects.
Additionally, there are some cases that you didn't think about, for instance I can think about calling remove by giving an invalid task, so you may work a bit around the code below to handle the case where taskIndex is -1 (meaning that no item was found with that index).
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);
You are on the right path. Maybe the trouble you had with filter is because filter will return a new Array and not modify the current one. You could update your remove function and replace the line:
delete toDoList.capitalWeekday[task]
with
toDoList.capitalWeekday = toDoList.capitalWeekday.filter((item) => {return item !== task});
function remove(task, weekdayDue) {
let capitalWeekday = weekdayDue.charAt(0).toUpperCase() +
weekdayDue.slice(1);
// Assign new array with all elements but task
toDoList[capitalWeekday] = toDoList[capitalWeekday].filter(i => i !== task)
};
add('foo'...
add('bar'...
"{
"Baz": [
"Foo",
"Bar"
]
}"
remove('foo'...
"{
"Baz": [
"Bar"
]
}"
I am having a little trouble trying to achieve something. So I have some data
let data = [
{
"ID": 123456,
"Date": "2012-01-01",
"Irrelevant_Column_1": 123,
"Irrelevant_Column_2": 234,
"Irrelevant_Column_3": 345,
"Irrelevant_Column_4": 456
},
...
]
And I wanted to remove the irrelevant columns. So someone suggested using map
data = data.map(element => ({ID: element.ID, Date: element.Date}))
The problem is, I dont want to define the columns. I have the user select the columns to keep, and assign them to a variable. I can then do something like
let selectedId = this.selectedIdCol;
The issue is, I am unable to now use this within the map. I am trying
let selectedId = this.selectedIdCol;
this.parsed_csv = data.map(element => (
{ID: element.selectedId, Date: element.Date}
));
But that does not seem to work, just returns the date. Also, my IDE is saying that the variable is unused. So how can I use the selectedId variable as part of the map function?
Thanks
You can do using Bracket notation notation and helper function
Whenever you want to use variable to access property you need to use [] notation.
let data = [{"ID": 123456,"Date": "2012-01-01","column_1": 123,"column_2": 234,"column_3": 345,"column_4": 456},{"ID": 123456,"Date": "2018-10-01", "column_1": 123,"column_2": 234,"column_3": 345,"column_4": 46},]
function selectDesired(data,propName1,propName2){
return data.map(e=> ({[propName1]: e[propName1], [propName2]: e[propName2]}))
}
console.log(selectDesired(data, 'Date', 'column_4'))
The basic technique is illustrated here, assuming that the user's selected column_name is "ID"
let data = [
{
"ID": 123456,
"Date": "2012-01-01",
"Irrelevant_Column_1": 123,
"Irrelevant_Column_2": 234,
"Irrelevant_Column_3": 345,
"Irrelevant_Column_4": 456
}
];
let column_name = "ID";
let curated = data.map(element=>({[column_name]: element[column_name]}));
console.log(curated)
If you are wanting the user to be able to multi-select their columns,(assuming data from above is still in scope)
let user_selection = ["ID","Date"];
let curated = data.map(
(element)=>
{
let item = {};
user_selection.forEach(
(property)=>
{
item[property] = element[property];
}
return item;
}
);
To set up a function that can handle multiple calling situations without having a monstrously hack-and-patched source history, set up the function's signature to receive a spread list of properties.
If you wish to extend the capabilities to accept
a csv property list
an array of property names delivered directly
an array of property names
you can assume the properties argument in the signature to be an iterable of property groupings, having the most basic grouping be a singleton.
Commentary embedded within the sample code to expound in more detail
var getProjection = (data,...properties) =>
{
//+=================================================+
// Initialize the projection which will be returned
//+=================================================+
let projection = {};
//+=================================================+
// Set up the property mapping func
//+=================================================+
let safe_assign = (source, target ,propertyDesignator)=>
{
if(source[propertyDesignator])
{
target[propertyDesignator] = source[propertyDesignator];
}
};
//+=====================================================+
// Iterate the properties list, assuming each element to
// be a property grouping
//+=====================================================+
properties.forEach(
(propertyGroup)=>
{
//+-----------------------------------------------+
// If the propertyGroup is not an array, perform
// direct assignment
//+-----------------------------------------------+
if(!Array.isArray(propertyGroup))
{
//+-------------------------------------------+
//Only map the requested property if it exists
//+-------------------------------------------+
safe_assign(data,projection,propertyGroup);
}
//+-----------------------------------------------+
// If the propertyGroup *is* an array, iterate it
// This technique obviously assumes that your
// property groupings are only allowed to be one
// level deep. This is for accommodating distinct
// calling conventions, not for supporting a deeply
// nested object graph. For a deeper object graph,
// the technique would largely be the same, but
// you would need to recurse.
//+-----------------------------------------------+
if( Array.isArray(propertyGroup))
{
propertyGroup.forEach(
(property)=>
{
safe_assign(data,projection,property);
}
}
}
);
//+===================================+
// Return your projection
//+===================================+
return projection;
};
//+--------------------------------------+
//Now let's test
//+--------------------------------------+
let data = [
{ID:1,Foo:"Foo1",Bar:"Bar1",Baz:"Inga"},
{ID:2,Foo:"Foo2",Bar:"Bar2",Baz:"Ooka"},
{ID:3,Foo:"Foo3",Bar:"Bar3",Baz:"oinga",Floppy:"Floop"},
{ID:4,Foo:"Foo4",Good:"Boi",Bar:"Bar3"Baz:"Baz"}
];
//***************************************
//tests
//***************************************
var projection1 = getProjection(data.find(first=>first),"ID","Baz"));//=>{ID:1,Baz:"Inga"}
var projection2 = getProjection(data[0],["ID","Baz"]);//=>{ID:1,Baz:"Inga"}
var projection3 = getProjection(data[0],...["ID","Baz"]);//=>{ID:1,Baz:"Inga"}
var user_selected_properties = ["ID","Good","Baz"];
var projections = data.map(element=>getProjection(element,user_selected_properties));
//+=====================================+
// projections =
// [
// {ID:1,Baz:"Inga"},
// {ID:2,Baz:"Ooka"},
// {ID:3,Baz:"oinga"},
// {ID:4,Good:"Boi",Baz:"Baz"}
// ];
//+=====================================+
I'm trying to match and group objects, based on a property on each object, and put them in their own array that I can use to sort later for some selection criteria. The sort method isn't an option for me, because I need to sort for 4 different values of the property.
How can I dynamically create separate arrays for the objects who have a matching property?
For example, I can do this if I know that the form.RatingNumber will be 1, 2, 3, or 4:
var ratingNumOne = [],
ratingNumTwo,
ratingNumThree,
ratingNumFour;
forms.forEach(function(form) {
if (form.RatingNumber === 1){
ratingNumOne.push(form);
} else if (form.RatingNumber === 2){
ratingNumTwo.push(form)
} //and so on...
});
The problem is that the form.RatingNumber property could be any number, so hard-coding 1,2,3,4 will not work.
How can I group the forms dynamically, by each RatingNumber?
try to use reduce function, something like this:
forms.reduce((result, form) => {
result[form.RatingNumber] = result[form.RatingNumber] || []
result[form.RatingNumber].push(form)
}
,{})
the result would be object, with each of the keys is the rating number and the values is the forms with this rating number.
that would be dynamic for any count of rating number
You could use an object and take form.RatingNumber as key.
If you have zero based values without gaps, you could use an array instead of an object.
var ratingNumOne = [],
ratingNumTwo = [],
ratingNumThree = [],
ratingNumFour = [],
ratings = { 1: ratingNumOne, 2: ratingNumTwo, 3: ratingNumThree, 4: ratingNumFour };
// usage
ratings[form.RatingNumber].push(form);
try this its a work arround:
forms.forEach(form => {
if (!window['ratingNumber' + form.RatingNumber]) window['ratingNumber' + form.RatingNumber] = [];
window['ratingNumber' + form.RatingNumber].push(form);
});
this will create the variables automaticly. In the end it will look like this:
ratingNumber1 = [form, form, form];
ratingNumber2 = [form, form];
ratingNumber100 = [form];
but to notice ratingNumber3 (for example) could also be undefined.
Just to have it said, your solution makes no sense but this version works at least.
It does not matter what numbers you are getting with RatingNumber, just use it as index. The result will be an object with the RatingNumber as indexes and an array of object that have that RatingNumber as value.
//example input
var forms = [{RatingNumber:5 }, {RatingNumber:6}, {RatingNumber:78}, {RatingNumber:6}];
var results = {};
$.each(forms, function(i, form){
if(!results[form.RatingNumber])
results[form.RatingNumber]=[];
results[form.RatingNumber].push(form);
});
console.log(results);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HIH
// Example input data
let forms = [{RatingNumber: 1}, {RatingNumber: 4}, {RatingNumber: 2}, {RatingNumber: 1}],
result = [];
forms.forEach(form => {
result[form.RatingNumber]
? result[form.RatingNumber].push(form)
: result[form.RatingNumber] = [form];
});
// Now `result` have all information. Next can do something else..
let getResult = index => {
let res = result[index] || [];
// Write your code here. For example VVVVV
console.log(`Rating ${index}: ${res.length} count`)
console.log(res)
}
getResult(1)
getResult(2)
getResult(3)
getResult(4)
Try to create an object with the "RatingNumber" as property:
rating = {};
forms.forEach(function(form) {
if( !rating[form.RatingNumber] ){
rating[form.RatingNumber] = []
}
rating[form.RatingNumber].push( form )
})
I want to find strings that has data from the strings from the array 2 in the array1 and save result as separate uniq array.
As can you see I search for not exact values. From the array1 values I know only part of the information, and I want to find the complete strings, with that information, in array1. And at the end I want to save what I found. So, I don't have a problem with finding here, but a problem with saving in the valid single JSON.
Array examples:
Array #1:
{
"overflow": [
"id:address:name:location:email",
...
"id2:address2:name2:location2:email2"
]
}
Array #2:
[
"location:email",
...
"location2:email2"
]
Code:
resultArr: function() {
var arr1 = '/var/log/1.json';
var arr2 = '/var/log/2.json';
var arrResult = '/var/log/result.json';
var arr2Obj = JSON.parse(fs.readFileSync(arr2, 'utf-8'));
for (var i = 0; i < arr2Obj.length; i++) {
var arr1Obj = JSON.parse(fs.readFileSync(arr1, 'utf-8'));
arr1Obj.overflow = arr1Obj.overflow.filter(function(e) {
return e.includes(arr2Obj[i])
});
fs.appendFile(arrResult, JSON.stringify(arr1Obj, null, 2), 'utf-8');
}
}
My result:
[{
"overflow": [
"id:address:name:location:email"
]
}{
"overflow": [
"id54:address54:name54:location54:email56"
]
}{
"overflow": [
"id2:address2:name2:location2:email2",
"id6:address6:name6:location2:email2"
]
}
What I really want:
{
"overflow": [
"id:address:name:location:email",
"id54:address54:name54:location54:email56",
"id6:address6:name6:location2:email2",
"id2:address2:name2:location2:email2"
]
}
Instead of reading the file again and again, and appending to the result repeatedly, just do both actions only once. All the rest should happen in memory.
You will also get better results (no risk for duplicates in result) when you swap the loops: put the filter action as the outer loop. For the inner loop you can use some, since one match is enough for the entry to be included:
resultArr: function() {
var arr1 = '/var/log/1.json',
arr2 = '/var/log/2.json',
arrResult = '/var/log/result.json',
arr2Obj = JSON.parse(fs.readFileSync(arr2, 'utf-8')),
arr1Obj = JSON.parse(fs.readFileSync(arr1, 'utf-8'));
arr1Obj.overflow = arr1Obj.overflow.filter(function(e) {
return arr2Obj.some(function (f) {
return e.includes(f)
});
});
fs.writeFileSync(arrResult, JSON.stringify(arr1Obj, null, 2), 'utf-8');
}
At each iteration, you're creating a new object and appening it to a file.
JSON is not a good format to append to.
You're replacing the array instead of adding fields to it.
You can do it that way, it should work :
resultArr: () => {
let arr1 = '/var/log/1.json';
let arr2 = '/var/log/2.json';
let arrResult = '/var/log/result.json';
let arr2Obj = JSON.parse(fs.readFileSync(arr2, 'utf-8'));
let arr1Obj = JSON.parse(fs.readFileSync(arr1, 'utf-8')); // reading only one time
arr1Obj.overflow = arr2Obj.map(value => {
return arr1Obj.overflow.filter(e => return e.includes(value))
});
fs.writeFileSync(arrResult, JSON.stringify(arr1Obj, null, 2), 'utf-8'); //Writing only one time
}
Array.map() executes the closure for each field in your array and group all the values returned by the closure in another array.
I also replaced some keywords to make your code more ES6 compliant. I you really want to append, you should use CSV and not JSON.
If I console.log(localStorage.getItem("cartCache")), the result like this :
{"dataCache":[{"id":20,"quantity":1,"total":100000,"request_date":"27-08-2017 20:31:00"},{"id":53,"quantity":1,"total":200000,"request_date":"27-08-2017 20:38:00"}],"expired":"2017-08-28T03:55:21.521Z"}
I want to remove the data in the cache by index array
For example, When I remove index array = 0, the result to be like this :
{"dataCache":[{"id":53,"quantity":1,"total":200000,"request_date":"27-08-2017 20:38:00"}]}
Another example, When I remove index array = 1, the result to be like this :
{"dataCache":[{"id":20,"quantity":1,"total":100000,"request_date":"27-08-2017 20:31:00"}]}
How can I do it?
I try like this :
var deleteIndex = 1;
var retrievedObj = localStorage.getItem("cartCache")
delete retrievedObj['dataCache'][deleteIndex];
It seems that is not the right way
localStorage.getItem("cartCache") returns you two objects - dataCache and expired. If you want to remove the element n of dataCache, remove it by
localStorage.getItem("cartCache").dataCache.splice(n,1);
To fit it in your code:
var deleteIndex = 1;
var retrievedObj = localStorage.getItem("cartCache");
retrievedObj.dataCache.splice(deleteIndex,1);
Then console.log your localStorage again and you'll see the element removed.
You can use splice to remove an item from the array
// Clearing all localStorage value. No need to use below line in your code
localStorage.clear();
// to be stored object
var x = {
"dataCache": [{
"id": 20,
"quantity": 1,
"total": 100000,
"request_date": "27-08-2017 20:31:00"
}, {
"id": 53,
"quantity": 1,
"total": 200000,
"request_date": "27-08-2017 20:38:00"
}],
"expired": "2017-08-28T03:55:21.521Z"
}
// Initially storing it in local storage using JSON.stringify
localStorage.setItem('storeData', JSON.stringify(x));
// Once stored retrieving the value using JSON.parse
var getItem = JSON.parse(localStorage.getItem('storeData'));
// setting the dataCache with new array. The new array will be created as splice is used. splice is used to remove an item from array,
//0 is the index of the array, while second parameter 1 is to represent how many item to be removed starting from 0 ndex
getItem.dataCache = getItem.dataCache.splice(0, 1);
console.log(getItem); // the modified object
// after operation setting it to local storage
localStorage.setItem('storeData', JSON.stringify(getItem))
DEMO
Keyword "delete" deletes deleteIndex only in retrieveObj it doesn't update your localStorage value. In order to update localStorage use:
var deleteIndex = 1;
var retrievedObj = localStorage.getItem("cartCache")
delete retrievedObj['dataCache'][deleteIndex];
localStorage.setItem("cartCache", retrieveObj)