Data expression to add a calculated attribute to all features?

926
1
Jump to solution
05-17-2023 09:16 AM
Jay_Gregory
Regular Contributor

I'm trying to easily create a data expression that adds an attribute to each feature in a data set, but I'm getting stuck on how to add an attribute to an existing feature without creating a feature from scratch, including all pre-existing attributes.  

I get an execution error: "key not found - attributes.'

In short, do I have to create a brand new feature and manually reference each attribute I need, or is there an easy way to simply add an attribute to an existing feature. 

 

var portal = Portal('https://www.arcgis.com/');
var layer = FeatureSetByPortalItem(portal, itemid)
var features=[];
for (var i in layer) {
   var newvalue = some logic here
   i['attributes']['newattribute'] = newvalue
   Push(features,i)
}
return {
  geometryType:'',
  features:features
}

 

 

0 Kudos
1 Solution

Accepted Solutions
JohannesLindner
MVP Frequent Contributor

You have to create a new Featureset and copy the attributes. Luckily, you can do it in a loop, without too much manual work:

// define the new field(s)
var new_fields = [
    {name: "NewAttribute", type: "esriFieldTypeInteger"},
]

// create an empty featureset with existing and new fields
var out_fs = {
        fields: Splice(Schema(layer).fields, new_fields),
        geometryType: Schema(layer).geometryType',
        features: []
    }

// fill the featureset
for (var i in layer) {
    var att = {}
    // copy existing field values
    for(var field in i) {
        var value = i[field]
        att[field] = IIf(TypeOf(value) == "Date", Number(value), value)
    }
    // insert the new value(s)
    var new_value = 25
    att["NewAttribute"] = new_value
    // append the feature to the featureset
    Push(out_fs.features, {attributes: att, geometry: Geometry(i)})
}

// return
return Featureset(Text(out_fs))

Have a great day!
Johannes

View solution in original post

1 Reply
JohannesLindner
MVP Frequent Contributor

You have to create a new Featureset and copy the attributes. Luckily, you can do it in a loop, without too much manual work:

// define the new field(s)
var new_fields = [
    {name: "NewAttribute", type: "esriFieldTypeInteger"},
]

// create an empty featureset with existing and new fields
var out_fs = {
        fields: Splice(Schema(layer).fields, new_fields),
        geometryType: Schema(layer).geometryType',
        features: []
    }

// fill the featureset
for (var i in layer) {
    var att = {}
    // copy existing field values
    for(var field in i) {
        var value = i[field]
        att[field] = IIf(TypeOf(value) == "Date", Number(value), value)
    }
    // insert the new value(s)
    var new_value = 25
    att["NewAttribute"] = new_value
    // append the feature to the featureset
    Push(out_fs.features, {attributes: att, geometry: Geometry(i)})
}

// return
return Featureset(Text(out_fs))

Have a great day!
Johannes