1

I would like to know how to modify the array object by type in javascript, I have a object in which fields type if only array change to as shown below(neglect the image which is always the last element) in javascript

function modifyObject(ob){
  var result = ob.map(e=>{
    Array.isArray(e.fields) ? e.fields.map(i=>({i:i}) :  
    Object.assign({}, ...ob.map(elm=>(elm.fields)));
  }
  )
}
var r1 = this.modifyObject(obj1);
var r2 = this.modifyObject(obj2);
var obj1=[
  {
    fields: {"cn":"IN"},
    id: 0,
    group: "Active"
  }
]

var obj2 =[
  {
    fields: ["city","name","img.jpg"],
    id: 0,
    group: "Active"
  }
]

Expected Output:

//if fields type is array
  {
    fields: {city:"city", name:"name"}  
  }

//if fields type is object 
  {
    fields: {"cn":"IN"}
  }
6
  • how about img.jpg? what to you want to display with its key? Commented Sep 2, 2020 at 3:34
  • 1
    @elpmid thanks for reply, no need to add img.jpg,( image alwys present in last element of fields) Commented Sep 2, 2020 at 3:35
  • so, there is no logic... Commented Sep 2, 2020 at 3:43
  • Why are you not returning anything (result) from modifyObject function? Commented Sep 2, 2020 at 4:31
  • Why does this in var r1 = this.modifyObject(obj1); mean? Commented Sep 2, 2020 at 4:32

1 Answer 1

1

The problem is that your obj1 and obj2 are not objects, they're array containg one object each. modifiedObj would have to receive myObj[0], or you could modify it as I did:

function modifyObject(myObj) {
  let modifiedObj = myObj;
  if (Array.isArray(modifiedObj.fields)) {
    let objFields = {};
    modifiedObj.fields.forEach(field => objFields[field] = field);
    modifiedObj.fields = objFields;
  }
  return modifiedObj; 
}

var obj1 = {
  fields: {"cn":"IN"},
  id    : 0,
  group : "Active"
};
var obj2 = {
  fields: ["city","name","img.jpg"],
  id    : 0,
  group : "Active"
};

var r2 = modifyObject(obj2);
console.log(r2);

Let me know if it's unclear. Please give me a +rep if it helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.