MDF
MDF

Reputation: 1343

Getting Last Index Value in JSON

What is Wrong in below code? getting last index value.in all JSON Object

    let arr = ['apple','banana','cherry'];
    let dataJson=[];
    let json={}
    console.log('lent',arr.length);
    for(var i = 0; i<arr.length;i++) {
        json.name=arr[i];
        json.type="fruit";
        dataJson.push(json);    
    }   

Upvotes: 0

Views: 174

Answers (3)

mwilson
mwilson

Reputation: 12900

It looks like you're trying to convert your array of string fruit names in to a JavaScript Object. Currently, your code is always overwritting the name property with every iteration. I would suggest pushing an object in every iteration instead.

let arr = ['apple','banana','cherry'];
let dataJson = [];
console.log('lent',arr.length);
for(var i = 0; i <arr.length; i++) {
  dataJson.push({name: arr[i], type: 'fruit'} )
}

console.log(dataJson);



// Modern way of doing it with Array.map
const data = ['apple','banana','cherry'].map( d => ( { name: d, type: 'fruit' } ) );
console.log(data);

In other news, JSON is a string. You're working with a JavaScript Object.

Upvotes: 0

Bill Cheng
Bill Cheng

Reputation: 956

I would use map to do it

const arr = ['apple','banana','cherry']

const dataJson = arr.map(fruitName => ({name: fruitName, type: 'fruit'}))

console.log(dataJson)

Upvotes: 1

random
random

Reputation: 7891

You are passing the object reference within the array. In the last iteration the object will have cherry which is reflected in all objects passed within the array. Instead, use Object.assign to create new object.

let arr = ['apple','banana','cherry'];
    let dataJson=[];
    let json={}
    for(var i = 0; i<arr.length;i++) {
        json.name=arr[i];
        json.type="fruit";
        dataJson.push(Object.assign({}, json));    
    }   

console.log(dataJson);

You can achieve the same functionality using reduce.

let fruits = ['apple','banana','cherry'];

const output = fruits.reduce((a, fruit) => {
    a.push({"name": fruit, type: "fruit"});
    return a;
}, []);

console.log(output);

Upvotes: 1

Related Questions