0

I am writing in my save method but here am getting as a list of array. but wanted to convert to set of string.

   mySys: $scope.stringArrayToObjectArray($scope.editmySystems,"name");

$scope.editmySystems holds value-

 0 :f
  id: svg
  name:"JASSI"
 1 :f
  id: svg2
  name:"JASSYY" 

 length: 2

So for conversion i wrote one function-

   $scope.stringArrayToObjectArray = function(stringArray, fieldName)   {
    var objectArr = [];
    angular.forEach(stringArray, function(singleString) {

        objectArr[fieldName]=singleString.name;

    });
    return objectArr;
};

currently objectArr is returning as-

     name: "JASON2"

Expected o/p- objectArr should return-

     name: ["JASSI","JASSYY"]

Please suggest

5
  • What do you expect objectArr[fieldName]=singleString.name; to do? Commented Jun 6, 2016 at 21:19
  • I have updated my post sir.. kindly advise Commented Jun 6, 2016 at 21:19
  • @zzzzBov, while that is clearly the bug, I'm not sure if there is any reason to bring quite that tone to the discussion. Clearly he tried and put forth some effort in solving it. Commented Jun 6, 2016 at 21:21
  • @MikePerrenoud, please re-read that question as just a question without sarcasm or malintent. It was meant as a serious question of expectations. Commented Jun 7, 2016 at 0:58
  • @MikePerrenoud , zzzzBov - Sir, I will improve quality of question in coming days. I am pretty new to stack overflow. Commented Jun 7, 2016 at 5:16

3 Answers 3

1

Basically you could just use:

var stringArray = [{id: 'svg', name: 'JASSI'}];
var objectArr = [];

stringArray.map(function(item) {
    objectArr.push(item.name);
});

console.log(objectArr);
Sign up to request clarification or add additional context in comments.

Comments

0

It's close but you're setting indexes on an array which will be an object. Instead, simply append the field name.

$scope.stringArrayToObjectArray = function(stringArray, fieldName)   {
    var objectArr = [];

    angular.forEach(stringArray, function(singleString) {
        objectArr.push(singleString[fieldName]);
    });

    return objectArr;
};

Comments

0

You could use Array#map and a callback which returns the wanted value of the key of the object.

The map() method creates a new array with the results of calling a provided function on every element in this array.

function getValues(array, key) {
    return array.map(function (a) {
        return a[key];
    });
}

var data = [{ id: 'svg', name: 'JASSI' }, { id: 'svg2', name: 'JASSYY' }];

console.log(getValues(data, 'name'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.