Yudha Pratama
Yudha Pratama

Reputation: 71

How to add fields to array that have no property react js

I have an array like this:

[{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3}]

the question is, how can i define name like this

[{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3, name: ''}]

using array.map ?

Upvotes: 0

Views: 66

Answers (4)

ABGR
ABGR

Reputation: 5205

Here's an one-liner. Check if name exists on the element. If it is, return without doing anything, else attach the property name.

var arr = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3}];

var newArr = arr.map(i=> i.name ? i : {...i, name:''});

console.log(newArr)

Upvotes: 0

Yogesh Aggarwal
Yogesh Aggarwal

Reputation: 1115

Note: I am assuming that you're missing more properties other than the name too. This sol. will cover all of them. How about the ES6 power:

let arr = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3}];
let allProperties = [];

arr.forEach(item => {
  allProperties.push(...Object.keys(item));
});

let newArr = arr.map(item => {
  let newItem = {};
  allProperties.forEach(property => {
    newItem[property] = "";
  });
  return {...newItem, ...item};
});
console.log(newArr);

Upvotes: 0

Harmandeep Singh Kalsi
Harmandeep Singh Kalsi

Reputation: 3345

You can map to loop over the objects and then using the method hasOwnProperty on object check if there is name property or not , if not add that property to the object

var arr = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3}];

arr.map(obj => {

    if(!obj.hasOwnProperty("name")){
        obj['name'] ="";
    }
return obj;
})

console.log(arr);

Upvotes: 2

Nacho Zullo
Nacho Zullo

Reputation: 571

You could try this:

const arr = [{id: 1, name: 'one'}, {id: 2, name: 'two'}, {id: 3}]

const newArr = arr.map(elem => {
    if (elem.name) { 
        return {...elem, name: '' }; 
    } else { 
        return elem 
    } 
})

Upvotes: 1

Related Questions