Reputation: 3568
I'm trying to use the spread operator to populate a new object from an old object, without copying the pointer of the old object. But the new object comes out empty. :(
Here's my code:
const obj = {
a: 'a',
b: 'b',
c: 'c'
};
const test1 = Object.assign({}, ...obj);
const test2 = {};
console.log('obj', obj);
console.log('test1', test1);
console.log('test2', test2);
test1
should show up in the console with the same content as obj
, but it's empty.
What am I doing wrong? Is there another way of doing it, without using Object.assign()
?
(Also have this in a jsbin.)
UPDATE:
I've tried:
const test = {...obj};
But I keep getting Unexpected token on the first dot of the spread. It works in JSBin, but not on my local. So I'm thinking I may have done something wonky with Webpack or Babel.
Here's my webpack.config.js
:
var path = require('path');
const DEV = process.env.NODE_ENV === 'dev';
const PROD = process.env.NODE_ENV === 'prod';
module.exports = {
devtool: 'source-map',
entry: './src/index.js',
module: {
loaders: [{
test: /\.js$/,
loaders: ['babel-loader'],
exclude: /node_modules/
},{
test: /\.(png|jpg|gif)$/,
loaders: ['url-loader'],
exclude: /node_modules/
},{
test: /\.(css|sass|scss)$/,
use: ['style-loader', 'css-loader?importLoaders=2', 'sass-loader'],
// exclude: /node_modules/
},{
test: /\.(svg)$/,
use: ['file-loader'],
// exclude: /node_modules/
},
{
test: /\.(otf)(\?.*)?$/,
loader: 'url-loader?limit=10000&mimetype=application/font-sfnt'
}]
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/dist/',
filename: 'bundle.js'
}
}
And here's my .babelrc
:
{
"presets": ["env", "react"]
}
Upvotes: 1
Views: 2907
Reputation: 31014
When you spread an object you need to wrap it inside an object body (same goes for arrays):
const test1 = Object.assign({}, {...obj});
With that said, i don't see any benefit from combine Object.assign
with the object spread.
You could just do:
const test1 = {...obj};
Or this:
const test1 = Object.assign({}, obj);
Edit
I should mention that the object spread syntax is a proposal (in stage 3) and you need the babel plugin babel-plugin-transform-object-rest-spread
to support it.
Just do:
npm install --save-dev babel-plugin-transform-object-rest-spread
And add it in your .babelrc
file:
{
"plugins": ["transform-object-rest-spread"]
}
Upvotes: 4
Reputation: 197
The spread operator is not properly used in this case.
You just want: Object.assign({}, obj)
, alternatively: test1 = { ...obj }
. What you are doing is more like Object.assign({}, obj.a, obj.b, obj.c);
Upvotes: 0