-1

Im very new to jquery but im using the following code:

var lineParts = [];
$.each( chartData, function(k,v){
barParts.push({
    label: k,
    value: v
  });
});

How do I clip k to the first 3 characters of the string? For example I want Positive to become Pos. Ive tried using this but with no joy:

var lineParts = [];
$.each( chartData, function(k,v){
k = k.substring(0,3);
lineParts.push({
    label: k,
    value: v
  });
});
Tivie
  • 18,864
  • 5
  • 58
  • 77
Sam
  • 147
  • 3
  • 10

2 Answers2

2

You have mistaken function(k, v). It should be function(v,k),i.e (value, key)

var lineParts = [];
var chartData = ['positive','negative'];
$.each( chartData, function(v,k){
k = k.substring(0,3);
lineParts.push({
    label: k,
    value: v
  });
});

console.log(lineParts);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
-1
var a = 'Positive';
var b = a.slice(0,3); // b == 'Pos'

This is how you get required number of characters at the start of the string

n3u3w3lt
  • 56
  • 6
  • Not gonna down-vote as you're right, but this does not answer the question. – Reinstate Monica Cellio Aug 18 '17 at 13:40
  • @Archer the question asked is "How do I clip k to the first 3 characters of the string? ". The rest of the jQuery code is irrelevant to the string manipulating nature of the question, imho. – n3u3w3lt Aug 18 '17 at 13:49
  • The code he posted clearly shows how to do that already, so that is not the question. If you think the question is worded badly then you should comment on that, rather than posting an irrelevant answer. – Reinstate Monica Cellio Aug 18 '17 at 15:43