最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Create new object from value of another object in js - Stack Overflow

programmeradmin5浏览0评论

What I want to do is really simple and there is a syntax error that I can't understand:

I have an array that contains some objects, and I want to create another array using some value of those objects:

let fields = [{type:'a',label:'email'},{type:'b',label:'name'},{type:'a',label:'tel'}]
let respone = []

// different implementation
fields.map(item => {
   respone.push({item.label: ''}) } )
`Uncaught SyntaxError: Unexpected token .`


fields.map(item => {
   respone = [...response, {item.label: ''}]  } )
`Uncaught SyntaxError: Unexpected token .`



fields.map(item => {
   respone = [...response, {item['label']: ''}]  } )
`Uncaught SyntaxError: Unexpected token [`

and obviously the error is from creating the object {item['label']: ''}. What is the reason for those errors, and what is the best way to create new objects from the existing object values.

What I want to do is really simple and there is a syntax error that I can't understand:

I have an array that contains some objects, and I want to create another array using some value of those objects:

let fields = [{type:'a',label:'email'},{type:'b',label:'name'},{type:'a',label:'tel'}]
let respone = []

// different implementation
fields.map(item => {
   respone.push({item.label: ''}) } )
`Uncaught SyntaxError: Unexpected token .`


fields.map(item => {
   respone = [...response, {item.label: ''}]  } )
`Uncaught SyntaxError: Unexpected token .`



fields.map(item => {
   respone = [...response, {item['label']: ''}]  } )
`Uncaught SyntaxError: Unexpected token [`

and obviously the error is from creating the object {item['label']: ''}. What is the reason for those errors, and what is the best way to create new objects from the existing object values.

Share Improve this question asked Jan 26, 2019 at 16:40 MehdiMehdi 1,3603 gold badges17 silver badges40 bronze badges 1
  • 4 Try fields.map(({type, label}) => ({[label]: ''})) – Nenad Vracar Commented Jan 26, 2019 at 16:42
Add a ment  | 

4 Answers 4

Reset to default 6

So you have an array of objects, consisting of type and label. You want to make a "posite object" using that array. First thing, you don't want respone to be an array, you want it to be an object. Second, you want to name the key on respone to the value of item.label.

Try this code:

let fields = [{type:'a',label:'email'},{type:'b',label:'name'},{type:'a',label:'tel'}]

// Create an empty object
let respone = {}

// Iterate over the fields array, using each one to set the  key and value
//  on our respone object.
fields.forEach(item => { respone[item.label] = item.type} );

// Let's see how it looks!
console.log(respone);

Edit: Based on a ment, it doesn't really make sense to use .map() -- the purpose of that is to return a new array, usually of transformed data, based on the array values. In this case, it makes more sense to use Array.forEach(...), the code has been amended to this.

Well the error is how you're trying to define key.

item.label this need to be changed to [item.label] as you want puted key (which needs to evaluated first and than used as key )

let fields = [{type:'a',label:'email'},{type:'b',label:'name'},{type:'a',label:'tel'}]

let respone = []

fields.forEach(item => {
   respone.push({[item.label]: ''}) } )
   
console.log(respone)

what's the difference between item.label and [item.label] ?

[item.label] will resolve item.label first and than use as key and it need not to be a valid identifier

item.label try to use it directly as key which is not correct JS identifier in this case

for reference read here

If you want to transform the array into another array with the same number of elements, then you want map:

let fields = [{type:'a',label:'email'},{type:'b',label:'name'},{type:'a',label:'tel'}]
let response = fields.map(field => ({[field.label]: ''}));
console.log(response);

The return from map is an array so you don't need to create and push to separate storage; map does that for you.


If you want to create a new object with members based on the array content, reduce is what you want:

let fields = [{type:'a',label:'email'},{type:'b',label:'name'},{type:'a',label:'tel'}]
let response = fields.reduce((obj, field) => ({...obj, [field.label]: ''}), {});
console.log(response);

(If you don't mind the eslint warning, you can not create the temp objects during the reduce:)

let fields = [{type:'a',label:'email'},{type:'b',label:'name'},{type:'a',label:'tel'}]
let response = fields.reduce((obj, field) => {
    obj[field.label] = '';
    return obj;
}, {});
console.log(response);

This is because u r using a "variable" as an object key, you need to use a bracket to tell the browser this is a "variable", otherwise the browser will treat it as a string, but you can not use a "." in a key, so it throw an error "Uncaught SyntaxError: Unexpected token .":

You should write like this:

var fields = [{type:'a',label:'email'},{type:'b',label:'name'},{type:'a',label:'tel'}];
var respone = [];

fields.map(item => {
  respone.push({
    [item.label]: ''
  })
});

console.log(respone);

Or if you can't understand, this should help you to understand:

var fields = [{type:'a',label:'email'},{type:'b',label:'name'},{type:'a',label:'tel'}];
var respone = [];

fields.map(item => {
  let obj = {};
  obj[item.label] = '';
  respone.push(obj);
});

console.log(respone);

发布评论

评论列表(0)

  1. 暂无评论