简体   繁体   中英

How to change the object depending value type javascript?

How to change the nested object to new object in javascript.

I have a object obj in which if details is arrays, then take first array value as value in javascript.

function newObj(obj1) {
  let map = {};
  obj1.forEach(e => {
    let details = e.details;
    Object.values(details).forEach(value => {
      if (Array.isArray(value) && value.length > 0) {
        map[value[0]] = value[0];
      }
      else if (typeof value === 'object') {
        Object.values(value).forEach(val => { map[val] = val; });
      }
    })
  });
  return map;
}

var obj1 = [
  {
    details : {
      "info"  : ["stocks", "finance", ""],
      "sales" : ["analytics"]
    }
  }
];
var obj2 = [
  {
    details : {
      "city" : "SG"
    }
  }
];
var r1 = this.newObj(obj1);
var r2 = this.newObj(obj2);

Expected Output

//for obj1 (show only first value of array)
{
  info  : "stocks",
  sales : "analytics"
}
//obj2
{
  city : "SG"
}

I think you have overcomplicated this. Look at the example below. The logic goes like this:

  1. Iterate over details keys
  2. If a value under the key is an array, then create the key in the map and assign the value[0]
  3. If a value under the key is not an array, then simply copy its value into the map

And that's enough to achieve what you want.

 function newObj(obj){ let map = {}; obj.forEach(e => { let details = e.details; Object.keys(details).forEach(key => { var value = details[key]; if (Array.isArray(value) && value.length > 0){ map[key] = value[0]; } else { map[key] = value; } }); }); return map; } var obj1 = [ { details: { "info":["stocks","finance",""], "sales":["analytics"] } } ]; var obj2 = [ { details: { "city":"SG" } } ]; var r1 = newObj(obj1); var r2 = newObj(obj2); console.log(r1); console.log(r2);

Here's a very concise solution thanks to destructuring assignments:

function newObj(obj) {
    const [{ details }] = obj;
    const entries = Object.entries(details)
        .map(([key, value]) => ([key, Array.isArray(value) ? value[0] : value]));
    return Object.fromEntries(entries);
}

Live example:

 'use strict'; function newObj(obj) { const [{ details }] = obj; const entries = Object.entries(details) .map(([key, value]) => ([key, Array.isArray(value) ? value[0] : value])); return Object.fromEntries(entries); } const obj1 = [ { details: { info: ['stocks', 'finance', ''], sales: ['analytics'] } } ]; const obj2 = [ { details: { city: 'SG' } } ]; console.log(newObj(obj1)); console.log(newObj(obj2));

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