简体   繁体   中英

Transform javascript array of object in object with keys

Here what I have :

const datas = [
  {id: '/chiens', content: ['waf1','waf2']},
  {id: '/chats', content: ['miaou1','miaou2']},
  {id: '/oiseaux', content: ['cui1','cui2']}
]

Here what I want :

const datasFiltered = {
   chiens : ['waf1','waf2'],
   chats : ['miaou1','miaou2'],
   oiseaux : ['cui1','cui2']
}

How I can do that ? With reduce maybe ?

Thanks for your help !

You can use the function reduce for creating the desired result.

 const datas = [{id: '/chiens', content: ['waf1','waf2']},{id: '/chats', content: ['miaou1','miaou2']},{id: '/oiseaux', content: ['cui1','cui2']}], datasFiltered = datas.reduce((a, {id: [_, ...key], content}) => Object.assign(a, {[key.join("")]: content}), Object.create(null)); console.log(datasFiltered);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

Here is sample code.

 const datas = [ { id: "/chiens", content: ["waf1", "waf2"] }, { id: "/chats", content: ["miaou1", "miaou2"] }, { id: "/oiseaux", content: ["cui1", "cui2"] } ]; const updated = datas.reduce( (acc, curr) => ({ ...acc, [curr.id.split("/")[1]]: curr.content, // alternatively // [curr.id.slice(1)]: curr.content }), {} ); console.log(updated);

You should construct new object based on your data array, something like

    let newObj = {};    
    datas.foreach(item => {
    newObj[item['id']] = item['content'];  
    })

Map the array to an array of entries [key, value], and convert to an object with Object.fromEntries() :

 const datas = [ { id: "/chiens", content: ["waf1", "waf2"] }, { id: "/chats", content: ["miaou1", "miaou2"] }, { id: "/oiseaux", content: ["cui1", "cui2"] } ]; const result = Object.fromEntries(datas.map(({ id, content }) => [ id.replace('/', ''), content ])); console.log(result);

You can use forEach too to achieve this.

 const datas = [ {id: '/chiens', content: ['waf1','waf2']}, {id: '/chats', content: ['miaou1','miaou2']}, {id: '/oiseaux', content: ['cui1','cui2']} ] const result = {}; datas.forEach((el) => { const key = el.id.substring(1,(el.id.length)); result[key] = el.content; }); console.log(result)

You can do it as below

[
    { id: '/chiens', content: ['waf1', 'waf2'] },
    { id: '/chats', content: ['miaou1', 'miaou2'] },
    { id: '/oiseaux', content: ['cui1', 'cui2'] },
].reduce((acc, ele) => {
    const newContent = (acc[ele.id.replace('/', '')] = ele.content);
    return { ...acc, newContent };
}, {});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM