जावास्क्रिप्ट सरणी पुनः संरचना


16

मेरे पास छात्र और अभिभावकों के पते के साथ एक सरणी है।

उदाहरण के लिए,

  const users = [{
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'USA',
    relationship:'mother'
  },
  {
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'Spain',
    relationship:'father'
  },
  {
    id: 2,
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    parent_address: 'France',
    relationship:'father'
  }
];

मैं निम्नलिखित परिणाम के लिए इसे पुन: स्वरूपित करने की कोशिश कर रहा हूं।

const list = [
{
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent: [
        {
            parent_address: 'USA',
            relationship:'mother'
        },{
            parent_address: 'Spain',
            relationship:'father'
        }
    ]
},
{
    id: 2,
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    parent:[
        {
            parent_address: 'France',
            relationship:'father'
        }
    ]
}
];

अब तक मैंने निम्नलिखित तरीके आजमाए। मुझे यकीन नहीं है कि यह सही तरीका है या नहीं।

const duplicateInfo = [];
for (var i = 0; i < user[0].length; i++) {
    var parent = [];
    if (duplicateInfo.indexOf(user[0][i].id) != -1) {
        // Do duplicate stuff
    } else {
        // Do other
    }
    duplicateInfo.push(user[0][i].id);
}

1
तो संक्षेप में - भविष्य के पाठकों के लिए इसे आसान बनाने के लिए - आप एक वस्तु और ईमेल पते के मिलने पर एक वस्तु में और एक वस्तु को जोड़ना parent_addressऔर उन्हें मर्ज करना चाहते हैं। relationshipparent
लेविस

2
माता-पिता का पता कैसे लिया जा सकता है? उन्हें संबंधित करने के लिए किस संपत्ति का उपयोग किया जाना चाहिए? अग्रिम धन्यवाद! :)
स्टेपअप

अंत में कोड स्निपेट डेटा संरचना से मेल नहीं खाता है। आप const list = []पहली बार में कहते हैं , लेकिन नीचे आप स्पष्ट रूप से पुनरावृत्ति करके उस सूची पर पुनरावृति करते हैं user[0]। आपका उदाहरण कोड सुसंगत होना चाहिए।
TKoL

@ लुईस हां, मैं वैसा ही चाहता हूं जैसा आपने उल्लेख किया है।
कैथी

@SteUp, वे मान इसे मेरे मौजूदा db से प्राप्त करते हैं और छात्र और अभिभावक तालिका के साथ जुड़ते हैं। माता-पिता की तालिका में मेरे पास केवल छात्र की आईडी क्या है।
कैथी

जवाबों:


12

एक दृष्टिकोण .reduce()एक संचयकर्ता के रूप में एक वस्तु के साथ उपयोग करना होगा । प्रत्येक आईडी के लिए, आप एक संबंधित ऑब्जेक्ट को माता-पिता के सरणी के साथ संग्रहीत कर सकते हैं जिसे आप अपने .reduce()कॉलबैक में संलग्न कर सकते हैं जब भी आप उसी आईडी के साथ एक नई वस्तु का सामना करते हैं। फिर अपनी वस्तु से वस्तुओं का एक सरणी प्राप्त करने के लिए, आप उस Object.values()पर कॉल कर सकते हैं

नीचे उदाहरण देखें:

const users = [{ id: 1, name: 'John', email: 'johnson@mail.com', age: 25, parent_address: 'USA', relationship: 'mother' }, { id: 1, name: 'John', email: 'johnson@mail.com', age: 25, parent_address: 'Spain', relationship: 'father' }, { id: 2, name: 'Mark', email: 'mark@mail.com', age: 28, parent_address: 'France', relationship: 'father' } ];
const res = Object.values(users.reduce((acc, {parent_address, relationship, ...r}) => { // use destructuring assignment to pull out necessary values
  acc[r.id] = acc[r.id] || {...r, parents: []}
  acc[r.id].parents.push({parent_address, relationship}); // short-hand property names allows us to use the variable names as keys
  return acc;
}, {}));

console.log(res);

चूंकि आपने उल्लेख किया है कि आप जेएस के लिए नए हैं, इसलिए इसे और अधिक आवश्यक तरीके से समझना आसान हो सकता है (विवरण के लिए कोड टिप्पणी देखें):

const users = [{ id: 1, name: 'John', email: 'johnson@mail.com', age: 25, parent_address: 'USA', relationship: 'mother' }, { id: 1, name: 'John', email: 'johnson@mail.com', age: 25, parent_address: 'Spain', relationship: 'father' }, { id: 2, name: 'Mark', email: 'mark@mail.com', age: 28, parent_address: 'France', relationship: 'father' } ];

const unique_map = {}; // create an object - store each id as a key, and an object with a parents array as its value
for(let i = 0; i < users.length; i++) { // loop your array object
  const user = users[i]; // get the current object
  const id = user.id; // get the current object/users's id
  
  if(!(id in unique_map)) // check if current user's id is in the the object
    unique_map[id] = { // add the id to the unique_map with an object as its associated value 
      id: id,
      name: user.name,
      email: user.email,
      age: user.age,
      parents: [] // add `parents` array to append to later
    }
    
  unique_map[id].parents.push({ // push the parent into the object's parents array
    parent_address: user.parent_address,
    relationship: user.relationship
  });
}

const result = Object.values(unique_map); // get all values in the unique_map
console.log(result);


धन्यवाद, मैं विवरण की जांच करूंगा और आपके कोड को पढ़ने के लिए मैं मौजूद हूं।
कैथी

ऊह यह ठोस है। reduceकॉलबैक में विनाशकारी वस्तु अच्छी है, लेकिन शायद शुरुआत के लिए थोड़ा भारी है।
TKoL

1
@TKoL धन्यवाद, मैं कोशिश करूँगा और एक "सरल" संस्करण जोड़ूंगा
निक पार्सन

1
सरल संस्करण बहुत अच्छा लग रहा है!
TKoL

1
बहुत बहुत धन्यवाद। मैं आपके कोड को पढ़ता हूं और विशेष रूप से दूसरे कोड स्निपेट को समझना आसान है। अन्य सदस्यों के उत्तर की भी सराहना करें। फिर से, बहुत बहुत धन्यवाद दोस्तों।
कैथी

5

आप ऐरे को कम कर सकते हैं और एक ही आईडी वाले उपयोगकर्ता की खोज कर सकते हैं और इसमें मूल जानकारी जोड़ सकते हैं।

यदि उपयोगकर्ता नहीं मिला है, तो परिणाम सेट में एक नया उपयोगकर्ता जोड़ें।

const
    users = [{ id: 1, name: 'John', email: 'johnson@mail.com', age: 25, parent_address: 'USA', relationship: 'mother' }, { id: 1, name: 'John', email: 'johnson@mail.com', age: 25, parent_address: 'Spain', relationship: 'father' }, { id: 2, name: 'Mark', email: 'mark@mail.com', age: 28, parent_address: 'France', relationship: 'father' }],
    grouped = users.reduce((r, { parent_address, relationship, ...user }) => {
        var temp = r.find(q => q.id === user.id );
        if (!temp) r.push(temp = { ...user, parent: []});
        temp.parent.push({ parent_address, relationship });
        return r;
    }, []);

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }


2

इस तरह के डेटा को रीस्ट्रक्चर करना बहुत सामान्य है और Array.reduce()इसे कार्य के लिए डिज़ाइन किया गया है। यह चीजों को देखने का एक अलग तरीका है और कुछ के लिए इस्तेमाल हो रही है, लेकिन आप कोड लिखने के बाद कुछ बार यह दूसरी प्रकृति बन जाता है।

reduce() एक सरणी पर कहा जाता है और दो पैरामीटर लेता है:

  1. एक फ़ंक्शन जिसे सरणी में प्रत्येक तत्व के लिए बुलाया जाएगा
  2. प्रारंभिक मूल्य

आपके फ़ंक्शन को पहले रन के लिए शुरुआती मान के साथ प्रत्येक तत्व के लिए बुलाया जाता है या पिछले फ़ंक्शन कॉल के बाद के प्रत्येक रिटर्न के लिए वैल्यू एलीमेंट के साथ, एरे तत्व, इंडेक्स को मूल एरे में और मूल ऐरे को कम () किया जाता है। पर बुलाया गया था (अंतिम दो को आमतौर पर अनदेखा किया जाता है और शायद ही कभी आवश्यक होता है)। यह वस्तु या जो कुछ भी आप वर्तमान तत्व के साथ जोड़ रहे हैं, उसे वापस करना चाहिए, और यह वापसी मान आपके फ़ंक्शन के अगले कॉल के लिए पास हो जाता है।

इस तरह की चीजों के लिए मेरे पास आमतौर पर अद्वितीय कुंजी ( idआपके लिए) रखने के लिए एक वस्तु है , लेकिन मुझे लगता है कि आप एक सरणी वापस चाहते हैं। किसी सरणी में ऑब्जेक्ट और कुंजियों को मैप करने के लिए एक पंक्ति है और यह देखने के लिए कि आपने पहले से ही एक आईडी जोड़ दी है, यह array.find () के बजाय बिल्ड-इन ऑब्जेक्ट संपत्ति तंत्र का उपयोग करने के लिए अधिक कुशल है।

const users = [{
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'USA',
    relationship:'mother'
  },
  {
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'Spain',
    relationship:'father'
  },
  {
    id: 2,
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    parent_address: 'France',
    relationship:'father'
  }
];

let combined = users.reduce(
  // function called for each element in the array
  (previous, element) => {
    // previous starts out as the empty object we pass as the second argument
    // and will be the return value from this function for every other element
    
    // create an object for the id on our 'previous' object if it doesn't exist,
    // if it does exist we will trust the name, email, and age from the first
    // instance
    previous[element.id] = previous[element.id] || {
      id: element.id,
      name: element.name,
      age: element.age,
      parents: []
    };
    
    // now add parent
    previous[element.id].parents.push({
      parent_address: element.parent_address,
      relationship: element.relationship
    });
    
    // return our updated object, which will be passed to the next call
    // and eventually returned
    return previous;
  },
  {} // initial value is an empty object, no ids yet
);

// transform object into array with elements in order by key
let list = Object.keys(combined).sort().map(key => combined[key]);

console.dir(list);


1

आपको वर्तमान विधि का उपयोग करके दो बार पुनरावृति करने की आवश्यकता है। जटिलता हे (n ^ 2)। (लूप + इंडेक्सऑफ के लिए)

एक बेहतर तरीका सरणी को अनुक्रमित करना और दोहराव का पता लगाने और खोज के लिए सरणी कुंजी का उपयोग करना है।

उदाहरण के लिए:

const map = {};
users.forEach(user => {
    // Will return undefined if not exist
    let existing = map[user.id];
    if (!existing) {
        // If not exist, create new
        existing = {
            id: user.id,
            ...
            parents: [ {parent_address: user.parent_address, relationship: user.relationship ]
        }
    } else {
        // Otherwise, update only parents field
        // You can add other logic here, for example update fields if duplication is detected.
        existing.parents.push({parent_address: user.parent_address, relationship: user.relationship ]
        });
    }
    map[user.id] = existing;
})
// Convert the object to array
const list = map.values();

धन्यवाद, मैं विवरण की जांच करूंगा और आपके कोड को पढ़ने के लिए मैं मौजूद हूं।
कैथी

1
const users = [{
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'USA',
    relationship:'mother'
  },
  {
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'Spain',
    relationship:'father'
  },
  {
    id: 2,
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    parent_address: 'France',
    relationship:'father'
  }
];
const updatedUsers = users.map(user => {
    return {
    id: user.id,
    name: user.name,
    email: user.email,
    age: user.age,
    parent: [{
        relationship: user.relationship,
        parent_address: user.parent_address,
    }]
}
})

const list = updatedUsers.reduce((acc, user) => {
    const findIndex = acc.findIndex(eachUser => eachUser.id === user.id && eachUser.email === user.email);
    if (findIndex < 0) {
        acc.push(user);
        return acc;
    } else {
    acc[findIndex].parent.push(user.parent);
    return acc; 
    }
}, []);
console.log(list)

1
एक स्पष्टीकरण क्रम में होगा। जैसे, आपने क्या बदला? और क्यों?
पीटर मोर्टेंसन

1

आप Mapअद्वितीय वस्तुओं को संग्रहीत करने के लिए संग्रह का उपयोग कर सकते हैं और बस इसका उपयोग कर सकते हैं filter:

const unique = new Map(users.map(u=> 
    [u.id, {...u, parent: [...users.filter(f => f.id == u.id)]}]));

console.log(Array.from(unique, ([k, v])=> v)
    .map(s => ( { id: s.id, name: s.name, email: s.email, age:s.age, parent:s.parent })));

const users = [
  {
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'USA',
    relationship: 'mother'
  },
  {
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'Spain',
    relationship: 'father'
  },
  {
    id: 2,
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    parent_address: 'France',
    relationship: 'father'
  }
];

const unique = new Map(users.map(u=> 
    [u.id, {...u, parent: [...users.filter(f => f.id == u.id)]}]));

console.log(Array.from(unique, ([k, v])=> v).map(s => ( 
    { id: s.id, name: s.name, email: s.email, age:s.age, parent:s.parent })));


0

 const users = [{
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'USA',
    relationship:'mother'
  },
  {
    id: 1,
    name: 'John',
    email: 'johnson@mail.com',
    age: 25,
    parent_address: 'Spain',
    relationship:'father'
  },
  {
    id: 2,
    name: 'Mark',
    email: 'mark@mail.com',
    age: 28,
    parent_address: 'France',
    relationship:'father'
  }
];
ids = new Map()
for (const user of users) {
  var newuser;
  if (ids.has(user.id)) {
    newuser = ids.get(user.id);
  } else {
    newuser = {};
    newuser.id = user.id;
    newuser.name = user.name;
    newuser.email = user.email;
    newuser.age = user.age;
    newuser.parent = [];
  }
  relationship = {};
  relationship.parent_address = user.parent_address;
  relationship.relationship = user.relationship;
  newuser.parent.push(relationship)
  ids.set(user.id, newuser);
}
list = [ ...ids.values() ];
list.forEach((u) => {
  console.log(JSON.stringify(u));
});

हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.