Errand
Errand

Reputation: 129

move object properties in array

I have the following object:

const obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 4,
  condition: 'checked' // could be "unckecked" or anything else
  items: []
}

and I want to check if the condition === checked then I will have to move a and b inside items like this:

const obj = {
  c: 3,
  d: 4,
  condition: 'checked' // could be "unckecked" or anything else
  items: [{
       a: 1,
       b: 2,
  }]
}

I have tried splice and tried to loop through the object with for(of) but didn't manage to do it, any idea how?

Upvotes: 0

Views: 106

Answers (3)

Nick
Nick

Reputation: 147286

If you don't want to use delete, you can use a function to return a new object instead with the values moved as required:

const obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 4,
  condition: 'checked', // could be "unckecked" or anything else
  items: []
}

const moveit = ({ a, b, condition, items, ...rest}) => 
condition === 'checked' ? { ...rest, condition, items: [{ a, b }] } : { a, b, ...rest, condition, items };

console.log(moveit(obj))

Upvotes: 2

mplungjan
mplungjan

Reputation: 178421

If you do not want delete, try a reduce

You could make this a little more DRY if you mapped the keys to the item

let  obj = { a: 1, b: 2, c: 3, d: 4, condition: 'checked',  items: [] };

if (obj.condition ==="checked") {
  const keys = ["a","b"]
  obj = Object.entries(obj).reduce((acc,[key,val]) => {
    if (key === "items") acc[key] = [{ a:obj.a,  b:obj.b}];
    else if (!keys.includes(key)) acc[key] = val;
    return acc;
  },{})
}  

console.log(obj)

Older answer:

let  obj = { a: 1, b: 2, c: 3, d: 4, condition: 'checked',  items: [] };

if (obj.condition ==="checked") {
  obj.items.push({ a:obj.a,  b:obj.b})
  delete obj.a;
  delete obj.b;
}  

console.log(obj)

Upvotes: 2

0stone0
0stone0

Reputation: 44275

const obj = {
  a: 1,
  b: 2,
  c: 3,
  d: 4,
  condition: 'checked',
  items: []
};

// If condition equals 'checked'
if (obj.condition === 'checked') {
    
    // Move a and b into items
    obj.items.push({ 
      a: obj.a,
      b: obj.b
    });
    
    // Delete old key/values
    delete obj.a;
    delete obj.b;
}

// Show result
console.log(obj);

Upvotes: 1

Related Questions