2

This is my array data :

var  service: [{
                id: '1',
                name: 'gana',
                age: '21',
                spare: 'rinch',
            }];

I want to add an static empty array inside of this data,

It is possible to insert the empty arry into another array using the map function?

my expected result is :

 var service: [{
                id: '1',
                name: 'gana',
                age: '21',
                spare: 'rinch',
                all:[]
            }];

Give any solution or idea for me.

5 Answers 5

2

Just use forEach:

var  service = [{id: '1', name: 'gana', age: '21', spare: 'rinch'}];
service.forEach(e => e.all = []);
console.log(service);

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

1 Comment

where is map used as it is mentioned in question.
1

var  service= [{
                id: '1',
                name: 'gana',
                age: '21',
                spare: 'rinch',
            }];
 console.log(service);
service.forEach(e => e.all= []);
console.log(service);

Comments

1

With Array#map without mutating the original array.

This proposal uses Object.assign and builds a new object with the wanted new property.

var service = [{ id: '1', name: 'gana', age: '21', spare: 'rinch' }],
    withAll = service.map(o => Object.assign({}, o, { all: [] }));

console.log(withAll);
console.log(service);
.as-console-wrapper { max-height: 100% !important; top: 0; }

1 Comment

without mutating the original array. Good point!!, might be worth mentioning though that Object.assign, is not a deep copy.. Fine for flat objects like this though.
1

You can achieve that just with index like the following:

var service = [{
                id: '1',
                name: 'gana',
                age: '21',
                spare: 'rinch',
            }];
service[0].all = [];
console.log(service)

With map() as you mentioned in the question:

var service = [{
                id: '1',
                name: 'gana',
                age: '21',
                spare: 'rinch',
            }];
service = service.map(function(i){
  i.all=[]; return i;
});
console.log(service);

Comments

0

Using underscore map you can do that easily

_.map([{
    id: '1',
    name: 'gana',
    age: '21',
    spare: 'rinch',
}], function(i) { i.all = [];
    return i; });

To test visit to underscore open inspect and paste the code to see the result

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.