// New javascript objects**
let askNow = {
findingID: 234,
findingName: 'Vulnerabilities',
};
let shiftLeft = {
findingID: 456,
findingName: 'shiftVulnerabiities',
};
// Storing javascript objects in an array**
let sources = [askNow, shiftLeft];
// Adding new property**
const addNewProperty = function(src) {
src.forEach(function(srcs) {
srcs.findingStatus = 'open';
});
};
addNewProperty(sources);
console.log(sources);
// Error in Accessing the new property elsewhere**
const index = sources.findIndex(function(cur, i, arr) {
console.log(cur.findingStatus);
})
I have 2 Array of objects. In which one is the original array, and another array contains the modified array. The modified array can contain new objects, edited object, or deleted object in settingValueDtoList
Currently, I am writing code for a new record in settingValueDtoList. If I am adding some new object in any settingValueDtoList then its id will be like a0, or a1 or a2 like this. I am just iterating both arrays and checking if id is not present in the original array, it means it is a new object, I want to push that object into my addSettingArray variable.
How can I fetch that new record whose id is not present in the original array?
This is what I tried.
compareSetting(settingArray: Array<any>) {
console.log('abc', this.settingObject)
console.log('settingArray',settingArray)
let settingIndex = 0;
this.settingObject.forEach(unmodifiedSetting => {
let modifiedSetting = settingArray[settingIndex];
modifiedSetting.settingValueDtoList.forEach(editedSettingValue => {
unmodifiedSetting.settingValueDtoList.forEach(uneditedSettingValue => {
if(editedSettingValue.id != uneditedSettingValue.id) {
this.addSettingArray.push(editedSettingValue);
}
});
})
settingIndex++;
})
console.log('add', this.addSettingArray)
}
Try like this:
compareSetting(settingArray: Array<any>) {
console.log('abc', this.settingObject)
console.log('settingArray',settingArray)
let settingIndex = 0;
this.settingObject.forEach(unmodifiedSetting => {
let modifiedSetting = settingArray[settingIndex];
modifiedSetting.settingValueDtoList.forEach(editedSettingValue => {
let isNewEntry = true;
unmodifiedSetting.settingValueDtoList.forEach(uneditedSettingValue => {
if(editedSettingValue.id == uneditedSettingValue.id) {
isNewEntry = false;
}
});
if (isNewEntry){
this.addSettingArray.push(editedSettingValue);
}
})
settingIndex++;
})
console.log('add', this.addSettingArray)
}
Edit:
More abstract for better understanding:
array1.forEach(entry1 =>
{
let isNewEntry = true; // says if entry1 is not present in array2
array2.forEach(entry2 =>
{
if(entry1.id == entry2.id)
{
isNewEntry = false; // the entry1 was found in array2
}
});
if (isNewEntry)
{
// the entry1 was not found in array2 - do whatever you want here
}
});
this.journeyIds = ["source", "destination"];
this.journeyDetails = [];
this.journeyIds.map((id)=>{
this.journeyDetails.push({
id: this.el("#" + id).inputValue
});
});
I want array like [{Source : "LMP"}, {Destination : "LKO"}];
i.e I want to make Id as key in object
thank you!
It seems that you want the id as key of an object. Use [] around the id
this.journeyIds = ["source", "destination"];
this.journeyDetails = [];
this.journeyIds.map((id) => {
this.journeyDetails.push({[id] :
this.el("#"+id).inputValue});
});
I don't have the function this.el() so it's an array here, you could just replace it with the function call (this.el["#"+id].inputValue => this.el("#"+id).inputValue
this.journeyIds = ["source", "destination"];
this.journeyDetails = [];
this.el = {
"#source": {inputValue: "foo"},
"#destination": {inputValue: "bar"}
}
this.journeyIds.forEach((id) => {
let temp = {};
temp[id] = this.el["#"+id].inputValue;
this.journeyDetails.push(temp);
});
console.log(this.journeyDetails)
I am trying to change the property name /attr name of my json object.I try like that but nothing will change.I need to make json object after seen the input json and convert it like outjson
function changeData(data){
var title;
for(var i = 0; i < data.length; i++){
if(data[i].hasOwnProperty("displayName")){
data[i]["label"] = data[i]["displayName"];
delete data[i]["displayName"];
}
if(data[i].hasOwnProperty("displayDetail")){
data[i]["title"] = data[i]["displayDetail"];
delete data[i]["displayDetail"];
}
if(data[i].hasOwnProperty("inputType")){
if(data[i]["inputType"]=="NUMBER"){
data[i]["type"]="number"
}else if(data[i]["inputType"]=="TEXT"){
data[i]["type"]="text"
}else if(data[i]["inputType"]=="SWTICH"){
data[i]["type"]="select"
}
delete data[i]["inputType"];
}
}
console.log(data);
}
Try this - it's possibe to remove the if selection for inputType by creating a tiny lookup table from original value to new value:
function changeData(data) {
var map = { NUMBER: "number", TEXT: "text", SWITCH: "select" };
// data is an object - use for .. in to enumerate
for (var key in data.input) {
var e = data.input[key]; // alias for efficient structure dereferencing
e.label = e.displayName;
e.title = e.displayDetail;
e.type = map[e.inputType];
delete e.displayName;
delete e.displayDetail;
delete e.inputType;
}
};
There's really no need for the hasOwnProperty test these days - only use it if you think there's any risk that someone unsafely added to Object.prototype. jQuery manages without it quite happily, other modern code should do to.
If the mapping of field names was any longer I'd consider using another mapping table with another loop to remove the hard coded copy/delete pairs.
i have a nice Recursive function for that:
usage:
// replace list
var replacedObj = replaceAttrName(sourceObject, {foo: 'foooo', bar: 'baaar'});
so in your case you can easily do:
var newObj = replaceAttrName(json, {displayDetail: 'title', displayName: 'label', inputType: 'type'});
demo: http://jsfiddle.net/h1u0kq67/15/
the function is that:
function replaceAttrName(sourceObj, replaceList, destObj) {
destObj = destObj || {};
for(var prop in sourceObj) {
if(sourceObj.hasOwnProperty(prop)) {
if(typeof sourceObj[prop] === 'object') {
if(replaceList[prop]) {
var strName = replaceList[prop];
destObj[strName] = {};
replaceAttrName(sourceObj[prop], replaceList, destObj[strName]);
} else if(!replaceList[prop]) {
destObj[prop] = {};
replaceAttrName(sourceObj[prop], replaceList, destObj[prop]);
}
} else if (typeof sourceObj[prop] != 'object') {
if(replaceList[prop]) {
var strName = replaceList[prop];
destObj[strName] = sourceObj[prop];
} else if(!replaceList[prop]) {
destObj[prop] = sourceObj[prop];
}
}
}
}
return destObj;
}
If I am getting you right, you just want substitutions:
displayDetail => title
displayName => label
inputType => type.
I came up with the follwoing:
function changeData(data){
return JSON.parse(JSON.stringify(data).replace(/displayDetail/g, "title").replace(/displayName/g, "label").replace(/inputType/g, "type"));
}
Here is the Fiddle to play with.
Edit: I forgot replacements for "NUMBER", "TEXT" and "SWITCH".
function changeData(data){
return JSON.parse(JSON.stringify(data).replace(/displayDetail/g, "title").replace(/displayName/g, "label").replace(/inputType/g, "type").replace(/TEXT/g, "text").replace(/NUMBER/g, "number").replace(/SWITCH/g, "switch"));
}
I have this JSON file: http://danish-regional-data.googlecode.com/svn/trunk/danish_regional_data.json
How do I remove all the attribues within_5_km, within_10_km, within_25_km, within_50_km, within_100_km for all postcodes?
I have read this question: Remove a JSON attribute
$(document).ready(function() {
$.getJSON("post.json", function(data) {
var pc = data.postalcodes;
for (var id in pc) {
if(pc.hasOwnProperty(id)) {
for(var attr in pc[id]) {
if(pc[id].hasOwnProperty(attr) && attr.indexOf('within_') === 0) {
delete pc[id][attr];
}
}
}
}
$("#json").html(pc);
});
});
In ES2016 you can use destructing to pick the fields you want for the subset object.
//ES6 subset of an object by specific fields
var object_private = {name: "alex", age: 25, password: 123};
var {name,age} = object_private, object_public = {name,age}
//method 2 using literals
let object_public = (({name,age})=>({name,age}))(object_private);
//use map if array of objects
users_array.map(u=>u.id)
Go to the json url you provided and open the Firebug console. Then drop in the folloing code and execute it:
var p = document.getElementsByTagName('pre');
for(i=0; i < p.length; i++) {
var data = JSON.parse(p[i].innerHTML);
var pc = data.postalcodes;
// this is the code i gave you... the previous is jsut to pull it out of the page
// in Firebug - this works for me
for (var id in pc) {
if(pc.hasOwnProperty(id)) {
for(var attr in pc[id]) {
if(pc[id].hasOwnProperty(attr) && attr.indexOf('within_') === 0) {
console.log('Deleting postalcodes.'+id+'.'+attr);
delete pc[id][attr];
}
}
}
}
}
// assume data is the complete json
var pc = data.postalcodes;
for (var id in pc) {
if(pc.hasOwnProperty(id)) {
for(var attr in pc[id]) {
if(pc[id].hasOwnProperty(attr) && attr.indexOf('within_') === 0) {
delete pc[id][attr];
}
}
}
}
JSON truncated:
var data = {"postalcodes":
{"800":{"id":"800","name":"H\u00f8je Taastrup","region_ids":["1084"],"region_names":["Hovedstaden"],"commune_ids":["169"],"commune_names":["H\u00f8je-Taastrup"],"lat":"55.66713","lng":"12.27888", "within_5_km":["800","2620","2630","2633"],"within_10_km":["800","2600","2605","2620"]},
"900":{"id":"900","name":"K\u00f8benhavn C","region_ids":["1084"],"region_names":["Hovedstaden"],"commune_ids":["101"],"commune_names":["K\u00f8benhavns"],"lat":"55.68258093401054","lng":"12.603657245635986","within_5_km":["900","999"]},
"1417":{"commune_id":"390","region_id":"1085"}}};
var pc = data.postalcodes;
for (var id in pc) {
var entry = pc[id];
for(var attr in entry) {
if(attr.indexOf('within_') === 0) {
delete entry[attr];
}
}
}
console.dir(data); // your data object has been augmented at this point
you can also use regular expression
var data = {"postalcodes":
{"800":{"id":"800","name":"H\u00f8je Taastrup","region_ids":["1084"],"region_names":["Hovedstaden"],"commune_ids":["169"],"commune_names":["H\u00f8je-Taastrup"],"lat":"55.66713","lng":"12.27888", "within_5_km":["800","2620","2630","2633"],"within_10_km":["800","2600","2605","2620"]},
"900":{"id":"900","name":"K\u00f8benhavn C","region_ids":["1084"],"region_names":["Hovedstaden"],"commune_ids":["101"],"commune_names":["K\u00f8benhavns"],"lat":"55.68258093401054","lng":"12.603657245635986","within_5_km":["900","999"]},
"1417":{"commune_id":"390","region_id":"1085"}}};
var regexp = new RegExp("^within_", "i"); // case insensitive regex matching strings starting with within_
var pc = data.postalcodes;
for (var id in pc) {
var entry = pc[id];
for(var attr in entry) {
if(regexp.test(attr)) {
delete entry[attr];
}
}
}
console.dir(data);
I have written an npm module unset which exactly does this. You specify json paths similar to the json-path module until the leaf attribute that you want to remove.
let unset = require('unset');
let object = {a: { b: [ {x: 1}, {x: [{ e: 2} ]}]}};
let newObject = unset(object, ['/a/b[*]/x']);
Multiple paths are supported in the second argument
well you can do this:
var postalcodes = YOUR JSON;
for(var code in postalcodes)
{
delete postalcodes[code].within_5_km;
.
.
.
}
you will probably want to check if the code contains your properties...