For example I have this array, if I stringfy it it would be like this:
[{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}]
How can I do for remove from the 2 cars: the doors and price. And only leave in the array "car" and "id"? For example:
[{"car":"Toyota","ID":"1"},{"car":"Chevrolet","ID":"2"}]
Thank you!
let arr = [{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}]
let arr1 = arr.map(({car, ID}) => ({car, ID}));
let arr2 = arr.map(({Doors, price, ...remainingAttrs}) => remainingAttrs);
console.log('arr1:', arr1);
console.log('arr2:', arr2);
With ES6 syntax, you can deconstruct each object to create new one without writing a loop.
In your case, total number of fields remaining is same as the total number of deleted
Following are the two approaches:
If less number of fields are to be preserved, then you can go with:
const arr1 = arr.map(({car, ID}) => ({car, ID}))
If less number of fields are to be removed, then you can go with:
const arr2 = arr.map(({Doors, price, ...remainingAttrs}) =>
remainingAttrs)
You can use Array.prototype.map() to customise your result array, taking a callback function as parameter which returns a new customised object, having only car and ID properties, in each iteration.
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
This is how should be your code:
var results = arr.map(function(item){
return {car : item["car"], ID : item["ID"]}
});
Demo:
var arr = [{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}];
var results = arr.map(function(item){
return {car : item["car"], ID : item["ID"]}
});
console.log(JSON.stringify(results));
Adding to all other answers
Cleaner approach using ES6 syntax
var originalArray =[{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}];
var immutableArray = originalArray.map(({Doors, price, ...rest})=> rest);
console.log(immutableArray);
You must iterate over your array deleting the property on each object.
Example:
for (var i = 0; i < myArray.length; i++){
delete myArray[i].myProperty
}
Adding to the answers, with ES6 and to avoid mutation and some ESlint issues.
const Array = [{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},
{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}];
const newArray = Array.map((object) => {
const {car, ID} = object;
return {car, ID};
});
Check comment for explanation:
var array=[{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}];
var resultArr = array.map(function(obj){
//we take only key-value pairs we need using JS bracket notation
return {"car":obj["car"],"ID":obj["ID"]};
});
console.log(resultArr);
You would be looking for the delete operator to fully remove those properties. It could look something like this:
var array = [{"car":"Toyota","ID":"1", "Doors": "4", "price": "20.000"},{"car":"Chevrolet","ID":"2", "Doors": "2", "price": "15.000"}]
for (car of array) {
delete(car.Doors);
delete(car.price);
}
You could also look into using Array.splice() for faster performance on large arrays.
Related
I have an array and I need to order the data of it by the distance of a specific point.
Knowing that .sort() won't work since I'm dealing with coordinates, I've been using a library called Geolib which has a function called getPreciseLocation() which is exactly what I need, but it doesn't seem to work while iterating through an array.
Here is the array containing the data I will be using.
Data:
[
{
"id": "1",
"Point": "27.1597268, 40.6646601"
},
{
"id": "2",
"Point": "11.1640393, 49.648713"
},
{
"id": "3",
"Point": "26.1539253, 42.6599287"
},
{
"id": "4",
"Point": "21.1597268, 44.6646601"
},
{
"id": "5",
"Point": "10.1640393, 43.648713"
},
{
"id": "6",
"Point": "26.1539253, 61.6599287"
}
]
The code I've been trying to use to iterate through the array.
let DistancesFromUserLocation = [];
this.state.Data.forEach(item => {
DistancesFromUserLocation.push(geolib.getPreciseDistance({latitude: 30.1891168, longitude: 11.6226982}, item.Point))
})
As a disclaimer: I only need to get to receive the distance of each array object to a new array.
I've tried and researched many things and get around the solution, but just about thinking that I am getting to the solution, something would go wrong.
You need to push the generated distance each iteration to DistancesFromUserLocation array.
let DistancesFromUserLocation = [];
this.state.Data.forEach(item => {
// push each distance to `DistancesFromUserLocation`
DistancesFromUserLocation.push(
geolib.getPreciseDistance(
{latitude: 30.1891168, longitude: 11.6226982},
item.Point
);
)
})
Only then you can use the Array.sort().
console.log(DistancesFromUserLocation.sort());
EDIT:
Check my working example here at codesandbox.
Looking for a way to get only the objects in the 'test' object that contain either one of the 'asSrcElementsTypes' values
What is the best way to map over the array to check if they are any of those values? I keep getting errors with the below code when I try to map the array to see if it matches the key in the test object.
var asSrcElementsTypes = ['-input', '-src'];
var test = { "exitUrl":"googl.com", "otherData1":"otherData1" "F2-1_largerLegal-input": "F2-1_largerLegal-input", "F2-1_copy-font": "Ultra", "F2-3_copy-fontSize": "12", "F2-1_copy-input": "F2-1_copy-input", "F2-1_frameLegal-input": "Ultra", "F2-1_frameLegal-fontSize": "14", "F2-2_copy-input": "F2-2_copy-input", "F2-3_copy-input": "F2-3_copy-input", "F2-3_copy-font": "Medium", "F2-1_copy-fontSize": "10", "F2-1_product-src": "250/50/F2-1_product.png", "F2-2_copy-font": "Medium", "F2-2_copy-fontSize": "11", "F2-1_largerLegal-fontSize": "13"};
const allButMe = data.filter(function(value, key){ if(key.indexOf.indexOf(asSrcElementsTypes.map()) !== -1){return key}});
Do you mean something, like that?
const asSrcElementsTypes = ['-input', '-src'],
test = { "F2-1_largerLegal-input": "F2-1_largerLegal-input", "F2-1_copy-font": "Ultra", "F2-3_copy-fontSize": "12", "F2-1_copy-input": "F2-1_copy-input", "F2-1_frameLegal-input": "Ultra", "F2-1_frameLegal-fontSize": "14", "F2-2_copy-input": "F2-2_copy-input", "F2-3_copy-input": "F2-3_copy-input", "F2-3_copy-font": "Medium", "F2-1_copy-fontSize": "10", "F2-1_product-src": "250/50/F2-1_product.png", "F2-2_copy-font": "Medium", "F2-2_copy-fontSize": "11", "F2-1_largerLegal-fontSize": "13"},
result = Object.fromEntries(
Object
.entries(test)
.filter(([key,value]) =>
asSrcElementsTypes
.some(type =>
key.includes(type)))
)
console.log(result)
.as-console-wrapper{min-height:100%;}
Or, maybe, alternative .reduce()-based way:
const asSrcElementsTypes = ['-input', '-src'],
test = { "F2-1_largerLegal-input": "F2-1_largerLegal-input", "F2-1_copy-font": "Ultra", "F2-3_copy-fontSize": "12", "F2-1_copy-input": "F2-1_copy-input", "F2-1_frameLegal-input": "Ultra", "F2-1_frameLegal-fontSize": "14", "F2-2_copy-input": "F2-2_copy-input", "F2-3_copy-input": "F2-3_copy-input", "F2-3_copy-font": "Medium", "F2-1_copy-fontSize": "10", "F2-1_product-src": "250/50/F2-1_product.png", "F2-2_copy-font": "Medium", "F2-2_copy-fontSize": "11", "F2-1_largerLegal-fontSize": "13"},
result = Object
.keys(test)
.reduce((r,key) => (
asSrcElementsTypes.some(type =>
key.includes(type)) &&
(r[key]=test[key]), r), {})
console.log(result)
.as-console-wrapper{min-height:100%;}
I want to delete the property period_to and period_from but if i use delete.period_to or delete.period_to[0] it does not delete.
function someData(data)
{
var formkey = [];
var formval = [];
var ch = data;
var clen = ch.length;
for(var i =0; i < clen; i++){
formkey.push(ch[i].name);
formval.push(ch[i].value);
}
var result = {};
formkey.forEach((key, i) => result[key] = formval[i]);
delete result.table;
delete result.redirect_to;
delete result.dbres;
delete result.period_to;
delete result.period_from;
//console.log(result);
//
return result;
}
-- chrome console
{name: "qwerty", client_id: "1", user_id: "1", period_from[2]: "11", period_from[1]: "01", …}
client_id: "1"
name: "qwerty"
period_from[0]: "11"
period_from[1]: "01"
period_from[2]: "11"
period_to[0]: "111"
period_to[1]: "09"
period_to[2]: "11"
user_id: "1"
__proto__: Object
Few observations :
If your obj is like as per the -- chrome console section in OP. Then you should delete the object properties with exact name.
DEMO
var obj = {
"client_id": "1",
"name": "qwerty",
"period_from[0]": "11",
"period_from[1]": "01",
"period_from[2]": "11",
"period_to[0]": "111",
"period_to[1]": "09",
"period_to[2]": "11",
"user_id": "1"
};
delete obj["period_to[0]"];
delete obj["period_from[0]"];
console.log(obj);
If your object is like this :
var obj = {
"client_id": "1",
"name": "qwerty",
"period_from": ["11","01","11"],
"period_to[0]": ["111","09","11"],
"user_id": "1"
};
Then try below code :
var obj = {
"client_id": "1",
"name": "qwerty",
"period_from": ["11","01","11"],
"period_to": ["111","09","11"],
"user_id": "1"
};
delete obj.period_to;
delete obj.period_from;
console.log(obj);
Delete is an operator and not a function. Remove the period and replace with space.
delete data.period_to
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete
If you're trying to delete period_from[2], for example, you're going to have to put quotes around the key name as it's currently not valid. You can then use bracket notation to delete the property.
const obj = {
name: "qwerty",
client_id: "1",
user_id: "1",
"period_from[2]": "11",
"period_from[1]": "01"
}
delete obj['period_from[2]'];
console.log(obj)
You can pare down the first part of that to a single reduce function, should make it a lot more readable and easy to troubleshoot.
Also instead of trying to do a bunch of deletes afterward, you can test the properties upfront and only add the ones you want.
var propRgx = /^(table|redirect_to|dbres|period_to|period_from)/
function allowProperty(prop){
return !propRgx.test(prop) //if the property matches any of those, return false
}
function someData(data)
{
//All of the assignment can be replaced with this reduce, and instead of deleting afterward, you can test the properties inside of here:
var result = data.reduce(function(obj, t){
if(allowProperty(t.name)) obj[t.name] = t.value
return obj
}, {})
return result;
}
You can use rest and destructuring:
var obj = {name: "1", client_id: "1", user_id: "1", period_from: [], period_to: []};
var period_to, period_from;
({period_to, period_from, ...obj} = obj);
console.log(obj);
I have two json arrays like,
array1 = [{"quantity":"5","detailed_product_id":"1015","detailed_category_id":"9"}]
and
array2 = [{"quantity":"2","detailed_product_id":"1003","detailed_category_id":"9"}]
I have to combine these two arrays into one array like,
resultarray = [{"quantity":"5","detailed_product_id":"1015","detailed_category_id":"9"},{"quantity":"2","detailed_product_id":"1003","detailed_category_id":"9"}]
Please help me.
array1 = [{"quantity":"5","detailed_product_id":"1015","detailed_category_id":"9"}]
array2 = [{"quantity":"2","detailed_product_id":"1003","detailed_category_id":"9"}]
console.log(array1.concat(array2));
You can do this using Es 6 new feature:
array1=[{"quantity":"5","detailed_product_id":"1015","detailed_category_id":"9"}]
array2 = [{"quantity":"2","detailed_product_id":"1003","detailed_category_id":"9"}]
var combineJsonArray = [...array1, ...array2 ];
//output should be like this [ {"quantity":"5","detailed_product_id":"1015","detailed_category_id":"9"},
{"quantity":"2","detailed_product_id":"1003","detailed_category_id":"9"}]
Or You can put extra string or anything between two JSON array:
var array3= [...array1,"test", ...array2];
// output should be like this : [ {"quantity":"5","detailed_product_id":"1015","detailed_category_id":"9"},"test",
{"quantity":"2","detailed_product_id":"1003","detailed_category_id":"9"}]
Use the concat function.
var resultarray = array1.concat(array2);
Result shown below:
array1 = [{
"quantity": "5",
"detailed_product_id": "1015",
"detailed_category_id": "9"
}];
array2 = [{
"quantity": "2",
"detailed_product_id": "1003",
"detailed_category_id": "9"
}];
console.log(array1.concat(array2));
Try array.concat for this.
<!DOCTYPE html>
<html>
<head>
<script>
var json1 = [{
"quantity": "5",
"detailed_product_id": "1015",
"detailed_category_id": "9"
}];
var json2 = [{
"quantity": "2",
"detailed_product_id": "1003",
"detailed_category_id": "9"
}]
var json3 = json2.concat(json1);
console.log(json3)
</script>
</head>
</html>
I am using multidimensional array (not JSON) in Javascript.
var Ar = [
['1','2013','A','Name1','1','1','3','3','1','2','3','4',''],
['2','2014','B','Name2','1','2','3','1','1','2','3','5',''],
['3','2015','C','Name3','1','2','4','4','1','2','5','4','']
];
To send or store Array Ar to Firebase Cloud I use:
var data = new Firebase("xxxx.firebaseIO.com");
data.set(Ar);
I use this 2D array form a lot.
What option do I have to get or store individual data or array back from Firebase Cloud?
Like refresh and sync Array Ar with the Cloud
Store new data the cloud Ar[2][3] = "New Text"
Get value from the cloud var x = Ar[2][3]
Hope you can help
Thanks K
var array = [
['1','2013','A','Name1','1','1','3','3','1','2','3','4',''],
['2','2014','B','Name2','1','2','3','1','1','2','3','5',''],
['3','2015','C','Name3','1','2','4','4','1','2','5','4','']
];
var ref = new Firebase('https://xxxx.firebaseio.com/');
ref.set(array);
ref.on('value', function(snapshot) {
var value = snapshot.val();
console.log(value);
console.log(value[2][3]);
});
The output from the above is:
[["1", "2013", "A", "Name1", "1", "1", "3", "3", "1", "2", "3", "4", ""],
["2", "2014", "B", "Name2", "1", "2", "3", "1", "1", "2", "3", "5", ""],
["3", "2015", "C", "Name3", "1", "2", "4", "4", "1", "2", "5", "4", ""]]
"Name3"
Any time any part of the array changes, the value event will fire again and the on('value' callback will be invoked.
If you want to update the array, you have two options.
array[2][3] = "New Text";
ref.set(array);
This will send the entire array to Firebase. The alternative is to update the one the element at [2][3] straight in your database:
ref.child(2).child(3).set("Newest Text");
No matter which of the two approaches you use, the on('value' callback will be invoked again.
Check out this jsbin for a working version of the code: http://jsbin.com/nawatetuya/edit?js,console
This can be answered in the Angular Firebase API docs if you're using Angular.
Look for $save and $add to save and add data to Firebase. To get values from the database, you just have to assign a variable like
var obj = $firebaseObject(ref);
and you can get the data from the variable to the DOM like
$scope.data = obj;
Pretty simple.
You can manipulate the data before it reaches the DOM inside a factory or service first then use a controller to get or present information.