I have a JSON
data consists of many keys and values and I'm trying to extract some and not all keys and values. Here's my JSON
data:
"projectID": 1,
"projectName": "XXX",
"price": 0.2,
"regStart":{
"$date": "2021-12-15T16:00:00.00Z"
},
"regEnd":{
"$date": "2021-12-18T16:00:00.00Z"
},
"saleStart":{
"$date": "2021-12-20T20:00:00.00Z"
},
"saleEnd":{
"$date": "2021-12-15T20:00:00.00Z"
},
"totalRaise": 200000,
"totalSale": 50000,
"projectStatus": "Ongoing",
Now I only wanna store projectID, projectName and price. How do I do that? I've written some but not sure how to iterate this data and store into my empty object.
let result = []
for(let i=0;i<data.length;i ){
let tempRes = {}
// ...no idea how to do it
result.push(tempRes);
}
CodePudding user response:
const arr = {"projectID": 1,
"projectName": "XXX",
"price": 0.2,
"regStart":{
"$date": "2021-12-15T16:00:00.00Z"
},
"regEnd":{
"$date": "2021-12-18T16:00:00.00Z"
},
"saleStart":{
"$date": "2021-12-20T20:00:00.00Z"
},
"saleEnd":{
"$date": "2021-12-15T20:00:00.00Z"
},
"totalRaise": 200000,
"totalSale": 50000,
"projectStatus": "Ongoing"}
const result = {};
Object.keys(arr).forEach(key=>{
if(['projectID','projectName','price'].includes(key)) { // you can modify this as per your requirement
result[key] = arr[key];
}
});
console.log(result);
CodePudding user response:
You can access the property using dot notation. Here's an example:
var data = {
"projectID": 1,
"projectName": "XXX",
"price": 0.2,
"regStart": {
"$date": "2021-12-15T16:00:00.00Z"
},
"regEnd": {
"$date": "2021-12-18T16:00:00.00Z"
},
"saleStart": {
"$date": "2021-12-20T20:00:00.00Z"
},
"saleEnd": {
"$date": "2021-12-15T20:00:00.00Z"
},
"totalRaise": 200000,
"totalSale": 50000,
"projectStatus": "Ongoing"
}
var resultObj = {projectID: data.projectID, projectName: data.projectName, price: data.price}
console.log(resultObj)
CodePudding user response:
Here is a util function I wrote a while back.
const removeKeys = (obj, keys, associate = true) => {
const _obj = associate ? obj : JSON.parse(JSON.stringify(obj))
keys.forEach((key) => {
if (Object.hasOwnProperty.call(_obj, key)) {
delete _obj[key]
}
})
return _obj
}
Usage for your case:
const payload = removeKeys(data, ['regStart', 'regEnd', 'saleStart', 'saleEnd', 'totalRaise', 'totalSale', 'projectStatus'], false)
Here it is in action: JSFiddle