0

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 ?

1
  • 1
    Are you missing just a 'name' property or you need more properties that are also unknown? Commented Jul 10, 2020 at 2:57

4 Answers 4

2

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);

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

Comments

1

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 
    } 
})

Comments

0

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);

Comments

0

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)

Comments

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.