1

I have this part of an object :

js: {
    cwd: 'src/js',
    src: [ "src/js/*.js", "src/js/*.min.js" ],
    dest: 'dist/js'
}

How can I insert the cwd property into src property so it looks like the following?

src: [ `${cwd (or js.cwd)}/*.JS .. etc ]
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
Anton
  • 516
  • 1
  • 6
  • 22
  • Possible duplicate of [Self-references in object literal declarations](https://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – str Oct 24 '18 at 13:22

3 Answers3

0

You can do it using the Array#shift(), Array#map() and Array#push() methods like this:

js = [js].map(a => {
  a.src.push(a.cwd);
  delete a.cwd;
  return a;
}).shift();

Demo:

var js = {
  cwd: 'src/js',
  src: ["src/js/*.js", "src/js/*.min.js"],
  dest: 'dist/js'
};

js = [js].map(a => {
  a.src.push(a.cwd);
  delete a.cwd;
  return a;
}).shift();

console.log(js);
cнŝdk
  • 31,391
  • 7
  • 56
  • 78
0

With ES2018' spread operator:

const foo = {
    ...js,
  src: [...js.src, js.cwd]
}
Mati Tucci
  • 2,826
  • 5
  • 28
  • 40
0

What you want is a computed property so use a getter.

const js = {
    cwd: 'src/js',
    get src() {
      return [ "/*.js", "/*.min.js" ]
        .map(ending => this.cwd + ending)
     },
    dest: 'dist/js'
}

console.log(js)
marzelin
  • 10,790
  • 2
  • 30
  • 49