0

I have a array with json objects. some objects properties values I need to convert to number from string. I need to push converted number value json to new list. I tried using floatparse but didnt succeed. code

var json = [{
    "id" : "0", 
    "msg"   : "hi",
    "cost" : "250.24",
    "discount": "10"
},
{
    "id" : "1", 
    "msg"   : "there",
    "cost" : "45.00",
    "discount": "0"
}];

var  json1 = [];

for (var key in json) {
       if (json.hasOwnProperty(key)) {
    
          for (const prop in json[key]) {        
          const parsed = parseFloat(json[key][prop]);              
          res[key][prop] = isNaN(parsed) ? json[key][prop] : parsed;                                        
           //  need to  push  array of modified json object value converted to number from string into json1  
          }
         
       }
    }
1
  • Given your json input example, providing the expected json1 output would help. Commented Oct 9, 2021 at 6:22

2 Answers 2

1

your loop are wrong.

for (var key in json) => when you use loop over an array it's return item index not key

json.hasOwnProperty(key) => your json is an array you don't need to use hasOwnProperty it's for object

I wrote 2 way for you:

*: you can use + for convert string to number.

*: if you want loop over item keys you can use way1, check Object.entries, Object.keys, Object.values methods.

const json = [{
    "id" : "0", 
    "msg"   : "hi",
    "cost" : "250.24",
    "discount": "10"
},
{
    "id" : "1", 
    "msg"   : "there",
    "cost" : "45.00",
    "discount": "0"
}];

//way1
const json1 = json.map((item)=>{
    return Object.entries(item).reduce((pre,[key,value])=>{
        const parsed = +value
        pre[key] = isNaN(parsed) ? value : parsed
        return pre
    },{})
})
console.log('json1',json1)

//way2
const json2 = json.map((item)=>{
    return {
        "id": +item.id,
        "msg": item.msg,
        "cost": +item.cost,
        "discount": +item.discount,
    }
})
console.log('json2',json2)

Sign up to request clarification or add additional context in comments.

7 Comments

for (var key in json) will give you key (index), not the values, you're thinking for (var key of json)
Run for (var key in [1,2,3]) console.log(key) vs for (var key of [1,2,3]) console.log(key)
yes i forgot to write index
yes way 1 works but order of objects is changed. cost becomes 1st. objects are n numbered. dynamic. I need in same order[{ "id" : 0, "msg" : "hi", "cost" : 250.24, "discount": 10 },...]
yes, because loop over item keys. I wrote way1 like your code. and loop over keys.
|
1

As objects

I prefer a map solution:

var json = [{
    "id": "0",
    "msg": "hi",
    "cost": "250.24",
    "discount": "10"
  },
  {
    "id": "1",
    "msg": "there",
    "cost": "45.00",
    "discount": "0"
  }
];

const json1 = json.map(obj =>
  Object.fromEntries(Object.entries(obj).map(([key, value]) => {
    const parsedValue = parseFloat(value);
    return [
      key,
      isNaN(parsedValue) ? value : parsedValue
    ];
  })));

console.log(json1);

To take it back to loops however:

var json = [{
    "id": "0",
    "msg": "hi",
    "cost": "250.24",
    "discount": "10"
  },
  {
    "id": "1",
    "msg": "there",
    "cost": "45.00",
    "discount": "0"
  }
];

const json1 = [];

for (const obj of json) {
  const mappedObj = {};

  for (const [key, value] of Object.entries(obj)) {
    const parsedValue = parseFloat(value);
    mappedObj[key] = isNaN(parsedValue) ? value : parsedValue;
  }

  json1.push(mappedObj);
}

console.log(json1);

As arrays

var json = [[
    {key:"id", value:"0"},
    {key:"msg", value:"hi"},
    {key:"cost", value:"250.24"},
    {key:"discount", value:"10"}
  ],
  [
    {key:"id", value:"1"},
    {key:"msg", value:"there"},
    {key:"cost", value:"45.00"},
    {key:"discount", value:"0"}
  ]
];

const json1 = json.map(obj =>
  obj.map(({key, value}) => {
    const parsedValue = parseFloat(value);
    return {
      key,
      value: isNaN(parsedValue) ? value : parsedValue
    };
  }));

console.log(json1);

3 Comments

output is like this[{ cost: 250.24, discount: 10, id: 0, msg: "hi" }, { cost: 45, discount: 0, id: 1, msg: "there" }] not in order
Two things, in my browser, I hit Run code snippet and I get them put out in order [{"id": 0,"msg": "hi","cost": 250.24,"discount": 10},{"id": 1,"msg": "there","cost": 45,"discount": 0}] Second thing you should NOT be relying on property order of js objects. It is not guaranteed, and we've just proven that with different results.
If order matters, I'd suggest a different data structure. Either represent the objects as arrays instead or use a Map. Reference

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.