0

Say I have an array of object::

const banana = [{"a":"ann","b":"bann","det":[{"c":"cat","d":"dog"},{"c":"conn","d":"donn"}]}, {"a":"auu","b":"buu","det":[{"c":"camel","d":"damel"},{"c":"coww","d":"doww"}]}]

I want to transform this array of object in this form::

const banana =  [{"a":"ann","b":"bann","c":"cat","d":"dog"}, {"a":"ann","b":"bann","c":"conn","d":"donn"}, {"a":"auu","b":"buu","c":"camel","d":"damel"}, {"a":"auu","b":"buu","c":"coww","d":"doww"}]

As you can see array of object inside array of object have merged and duplicated.

I tried as:

const apple = []

for(let i = 0; i<banana.length;i++){
    for(let j = 0;j<banana[i].det.length;j++{
    apple.push(banana[i].det[j])
    }
}
console.log(apple)

**OUTPUT: [{c: "cat", d: "dog"},{c: "conn", d: "donn"},{c: "camel", d: "damel"},{c: "coww", d: "doww"}]**

But I'm looking for the O/P as:

[{"a":"ann","b":"bann","c":"cat","d":"dog"}, {"a":"ann","b":"bann","c":"conn","d":"donn"}, 
{"a":"auu","b":"buu","c":"camel","d":"damel"}, {"a":"auu","b":"buu","c":"coww","d":"doww"}]

But I'm unable to form logic. I'm still trying but if i could get some guidance that would be really helpful.

**EDIT:**So I've come up with an idea using spread operator:

let enamel = {}

for(let i = 0; i<banana.length;i++){
    for(let j = 0;j<banana[i].det.length;j++){
     employee = {
        ...banana[j],
        ...banana[i].det[j]
    };
    }
}

It gives the output as:

console.log(enamel) 
{a: "auu", b: "buu", det: Array(2), c: "coww", d: "doww"}

But I want to have all the objects in an array as previously stated.

0

5 Answers 5

1

You can use this logic, which copies over initial object, adds extra properties, drops the det array, and flatten the result

function extras(obj) {
  // create a copy of the current context (initial obj)
  // and add all properties from the extra object
  obj = Object.assign({}, this, obj);
  // but delete the `det` from the copy
  delete obj.det;
  // and return the object
  return obj;
}

// per each array object ...
banana
  .map(
    // and per each det ...
    obj => obj.det.map(extras, obj)
  )
  // flatten the final array of objects
  .flat();
Sign up to request clarification or add additional context in comments.

Comments

0

You just have to extract a and b from object in banana. I have used destructuring to extract it.

const banana = [{ "a": "ann", "b": "bann", "det": [{ "c": "cat", "d": "dog" }, { "c": "conn", "d": "donn" }] }, { "a": "auu", "b": "buu", "det": [{ "c": "camel", "d": "damel" }, { "c": "coww", "d": "doww" }] }]
const apple = []

for (let i = 0; i < banana.length; i++) {
  for (let j = 0; j < banana[i].det.length; j++) {
      const {a,b} = banana[i];
      const {c,d} = banana[i].det[j];
      apple.push({a,b,c,d});
    }
}
console.log(apple)

7 Comments

Thank you this is exactly what I wanted. But could you help me understand line 6 i.e.: const {a,b} = banana[i]; What exactly it does?
developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… You can read about this on the link. It is like accessing variable a and b.
I cannot use this solution as spread operator give some random value in node js. Can you suggest some other way?
Does it take browser property as well...because in response it gives me:: "__parentArray" and other random keys along with the value
No, it shouldn't unless your object is different. You can use extract both c and d. You can check now if the current solution works for you.
|
0

You can do this:

const banana = [
        { 
            "a": "ann", 
            "b": "bann",
            "det": [{ "c": "cat", "d": "dog" }, { "c": "conn", "d": "donn" }]
        }, 

        { 
            "a": "auu", 
            "b": "buu", 
            "det": [
                { "c": "camel", "d": "damel" },
                { "c": "coww", "d": "doww" }
            ] 
        }
    ]

    const result = [];
    banana.forEach( b =>{
        b.det.forEach(d =>{
            result.push({
                a: b.a,
                b: b.b,
                c: d.c,
                d: d.d
            });
        });
    });

    console.log(result);

Comments

0

Try this

const banana = [{"a":"ann","b":"bann","det":[{"c":"cat","d":"dog"},{"c":"conn","d":"donn"}]}, {"a":"auu","b":"buu","det":[{"c":"camel","d":"damel"},{"c":"coww","d":"doww"}]}]

const output = []

for (const { a, b, det } of banana) {
  for (const animal of det) {
    output.push({a, b, ...animal })
  }
}

console.log(output)

Comments

0

I think you want to do it like this in case you want to avoid manually take a and b and other property except 'det' properties

function getResult(banana) {

    const answer = [];

    banana.forEach(element => {
        const arrayData = element['det'];
        delete element['det'];
        // remove the 'del' property temporarily

        arrayData.forEach(subElement  => {
            answer.push({
                ...element, // basically spread operator to make copy of all properties each time
                ...subElement
            });
        });

        // restore the 'del' proprty
        element['det'] = arrayData;
    });

    console.log("the result is : ", answer);
    return answer;
}

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.