生徒と保護者のアドレスを含む配列があります。
例えば、
const users = [{
id: 1,
name: 'John',
email: '[email protected]',
age: 25,
parent_address: 'USA',
relationship:'mother'
},
{
id: 1,
name: 'John',
email: '[email protected]',
age: 25,
parent_address: 'Spain',
relationship:'father'
},
{
id: 2,
name: 'Mark',
email: '[email protected]',
age: 28,
parent_address: 'France',
relationship:'father'
}
];
これを次の結果に再フォーマットしようとしています。
const list = [
{
id: 1,
name: 'John',
email: '[email protected]',
age: 25,
parent: [
{
parent_address: 'USA',
relationship:'mother'
},{
parent_address: 'Spain',
relationship:'father'
}
]
},
{
id: 2,
name: 'Mark',
email: '[email protected]',
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つのアプローチは.reduce()
、オブジェクトをアキュムレータとして使用することです。IDごとに、同じIDを持つ新しいオブジェクトに遭遇したときにいつでも.reduce()
コールバックに追加できる、親配列に関連付けられたオブジェクトを格納できます。次に、あなたのオブジェクトからオブジェクトの配列を取得するには、呼び出すことができObject.values()
、その上に
以下の例を参照してください。
const users = [{ id: 1, name: 'John', email: '[email protected]', age: 25, parent_address: 'USA', relationship: 'mother' }, { id: 1, name: 'John', email: '[email protected]', age: 25, parent_address: 'Spain', relationship: 'father' }, { id: 2, name: 'Mark', email: '[email protected]', 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);
JSを初めて使用するとおっしゃっていたので、より命令的な方法で理解する方が簡単な場合があります(詳細についてはコードコメントを参照してください)。
const users = [{ id: 1, name: 'John', email: '[email protected]', age: 25, parent_address: 'USA', relationship: 'mother' }, { id: 1, name: 'John', email: '[email protected]', age: 25, parent_address: 'Spain', relationship: 'father' }, { id: 2, name: 'Mark', email: '[email protected]', 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);
配列を減らして同じIDのユーザーを検索し、それに親情報を追加することができます。
ユーザーが見つからない場合は、結果セットに新しいユーザーを追加します。
const
users = [{ id: 1, name: 'John', email: '[email protected]', age: 25, parent_address: 'USA', relationship: 'mother' }, { id: 1, name: 'John', email: '[email protected]', age: 25, parent_address: 'Spain', relationship: 'father' }, { id: 2, name: 'Mark', email: '[email protected]', 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; }
このようなデータの再構築は非常に一般的でありArray.reduce()
、タスク用に設計されています。これは物事を見る別の方法であり、慣れるのに少し時間がかかりますが、コードを数回書くと、それは第二の性質になります。
reduce()
配列で呼び出され、2つのパラメーターを取ります。
あなたの次に呼び出される関数の各要素の配列要素に沿って第1の実行または後続の各実行の前の関数呼び出しからの戻り値の開始値と、元の配列へのインデックス、および低減元の配列()呼び出されました(最後の2つは通常無視され、ほとんど必要ありません)。オブジェクトまたは現在の要素を追加して構築しているものを返す必要があり、その戻り値は関数の次の呼び出しに渡されます。
このようなことのために、私は通常、(id
あなたのために)一意のキーを保持するオブジェクトを持っていますが、配列を返したいと思います。これは、オブジェクトとキーを配列にマップするための1行であり、array.find()の代わりに組み込みのオブジェクトプロパティメカニズムを使用して、IDが既に追加されているかどうかを確認する方が効率的です。
const users = [{
id: 1,
name: 'John',
email: '[email protected]',
age: 25,
parent_address: 'USA',
relationship:'mother'
},
{
id: 1,
name: 'John',
email: '[email protected]',
age: 25,
parent_address: 'Spain',
relationship:'father'
},
{
id: 2,
name: 'Mark',
email: '[email protected]',
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);
現在の方法を使用して2回繰り返す必要があります。複雑さはO(n ^ 2)です。(forループ+ indexOf)
より良い方法は、配列にインデックスを付け、重複の検出と検索に配列キーを使用することです。
例えば:
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();
const users = [{
id: 1,
name: 'John',
email: '[email protected]',
age: 25,
parent_address: 'USA',
relationship:'mother'
},
{
id: 1,
name: 'John',
email: '[email protected]',
age: 25,
parent_address: 'Spain',
relationship:'father'
},
{
id: 2,
name: 'Mark',
email: '[email protected]',
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)
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: '[email protected]',
age: 25,
parent_address: 'USA',
relationship: 'mother'
},
{
id: 1,
name: 'John',
email: '[email protected]',
age: 25,
parent_address: 'Spain',
relationship: 'father'
},
{
id: 2,
name: 'Mark',
email: '[email protected]',
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 })));
const users = [{
id: 1,
name: 'John',
email: '[email protected]',
age: 25,
parent_address: 'USA',
relationship:'mother'
},
{
id: 1,
name: 'John',
email: '[email protected]',
age: 25,
parent_address: 'Spain',
relationship:'father'
},
{
id: 2,
name: 'Mark',
email: '[email protected]',
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));
});
Reba McEntire が息子の Shelby Blackstock と共有しているクリスマスの伝統について学びましょう。
メーガン・マークルとマライア・キャリーが自然な髪の上でどのように結合したかについて、メーガンの「アーキタイプ」ポッドキャストのエピソードで学びましょう.
ハリー王子が家族、特にチャールズ王とウィリアム王子との関係について望んでいると主張したある情報源を発見してください。
ワイノナ・ジャッドが、母親のナオミ・ジャッドが亡くなってから初めての感謝祭のお祝いを主催しているときに、彼女が今では家長であることをどのように認識したかを学びましょう.
Air travel is far more than getting from point A to point B safely. How much do you know about the million little details that go into flying on airplanes?
The world is a huge place, yet some GeoGuessr players know locations in mere seconds. Are you one of GeoGuessr's gifted elite? Take our quiz to find out!
ドナルドグローバーの「ディスイズアメリカ」は、それがビデオ自体(5月6日にデビューしてから1億900万回以上視聴された)であろうと、ビデオに関する公の言説(ひいてはグローバー、別名)であろうと、先週避けられませんでした。幼稚なガンビーノ、彼自身)。現在、「ディス・イズ・アメリカ」はNo.でデビューします。
Trailer Happy Hourにようこそ。オーディオビジュアルのヴァルハラでは、すべての優れた映画のプロモーションが、あなたの愛、注目、クリックのために永遠に戦います。今日は、ワイルドパーティー、警察が関与する銃撃、80年代の漫画の雑学クイズを打ち破る怒り狂ったウィルアーネットがいるので、すぐに飛び込みましょう。
(写真:パトリック・スミス/ゲッティイメージズ)削除されたInstagramの投稿で、女優のヘザー・リンドがジョージHWを主張しました
ロシアのフィギュアスケーター、カミラ・バリエバが関与したドーピング事件が整理されているため、チームは2022年北京冬季オリンピックで獲得したメダルを待っています。
何千人ものAmazonの買い物客がMulberry Silk Pillowcaseを推奨しており、現在販売中. シルクの枕カバーにはいくつかの色があり、髪を柔らかく肌を透明に保ちます。Amazonで最大46%オフになっている間にシルクの枕カバーを購入してください
ラファイエット警察署は、「不審な男性が女性に近づいた」という複数の苦情を受けて、12 月にパデュー大学の教授の捜査を開始しました。
私たちの周りの世界と同じように、言語は常に変化しています。以前の時代では、言語の変化は数年または数十年にわたって発生していましたが、現在では数日または数時間で変化する可能性があります。
認知症を患っている 91 歳のアジア人女性が最近、47 番街のアウター サンセット地区でロメオ ロレンゾ パーハムに襲われました。伝えられるところによると、被害者はサンフランシスコの通りを歩いていたところ、容疑者に近づき、攻撃を受け、暴行を受けました。
Cómo mejoramos la accesibilidad de nuestro componente de precio, y cómo nos marcó el camino hacia nuevos saberes para nuestro sistema de diseño. Por Ana Calderon y Laura Sarmiento Leer esta historia en inglés.
“And a river went out of Eden to water the garden, and from thence it was parted and became into four heads” Genesis 2:10. ? The heart is located in the middle of the thoracic cavity, pointing eastward.