-4

I have some json file from url which I want to format. Problem is there i dont know how to get only titles of this objects. I think it should looks like: 1. Get JSON 2. Create an array which include only titles "C-402-621, C-393-643, C-389-643..." from this json.

Here is JSON

{  
   "data":{  
      "C-402-621":[  
         23944,
         21469,
         10160,
         "abc",
         0,
         0,
         ""
      ],
      "C-393-643":[  
         31424,
         21469,
         10160,
         "def",
         0,
         0,
         ""
      ],
      "C-389-643":[  
         31713,
         21469,
         10160,
         "gfd",
         0,
         0,
         ""
      ],
... and it goes like this 100+ times till end.

For example I want result looks like:

"402|621 393|643 389|643 ..."
Krystian
  • 15
  • 4

3 Answers3

1

You can use forEach loop and string manipulation. First using Object.keys we get all the keys of the data object. These keys then can be iterated one by one and with substr we can remove first 3 characters and using replace we can replace - by |

var a=[{  
   "data":{  
      "C-402-621":[  
         23944,
         21469,
         10160,
         "abc",
         0,
         0,
         ""
      ],
      "C-393-643":[  
         31424,
         21469,
         10160,
         "def",
         0,
         0,
         ""
      ],
      "C-389-643":[  
         31713,
         21469,
         10160,
         "gfd",
         0,
         0,
         ""
      ]}}]
     var data=Object.keys(a[0].data)
     data.forEach((e)=>{data[data.indexOf(e)]=e.substr(2).replace('-','|')})
     console.log(...data)
ellipsis
  • 12,049
  • 2
  • 17
  • 33
1
  1. First, you need the keys (within the data sub-object).
  2. Second, you need to split each key by the dashes.
  3. Next you need to grab the tail (ignoring the 'C')
  4. Then join the values with a pipe.
  5. Finally, you can join the processed keys with spaces.

var jsonData = {
  "data": {
    "C-402-621": [
      23944,
      21469,
      10160,
      "abc",
      0,
      0,
      ""
    ],
    "C-393-643": [
      31424,
      21469,
      10160,
      "def",
      0,
      0,
      ""
    ],
    "C-389-643": [
      31713,
      21469,
      10160,
      "gfd",
      0,
      0,
      ""
    ]
  }
};

console.log(Object.keys(jsonData.data).map(x => x.split('-').splice(1).join('|')).join(' '));
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

you can create a script in nodejs that reads the contents of the file, save it in a variable and pass them in the following function

var obj = { data: { .... } };
var keys = Object.keys(obj.data);

now keys contains an array of all the keys in your object. To print it like your example you could do

console.log(keys.join("|");
//"402|621 393|643 389|643 ..."
Haris Bouchlis
  • 2,366
  • 1
  • 20
  • 35