我有一个包含3个元素的数组...
每个元素都是一个以name
和arrayOfJSON
作为键的对象...
在arrayOfJSON
内可以有任意数量的JSON字符串作为元素...
我需要捕获数组Alex@gmail
和mess
都出现arrayOfJSON
的位置
结果应为:
position_of_mess = [0,2]
position_of_arrayOfJSON_for_position_of_mess_0 = [0]
position_of_arrayOfJSON_for_position_of_mess_2 = [1]
用于遍历混乱,用于遍历arrayOfJSON,以及用于Alex @ gmail的JSON.parse()。 要花几分钟时间进行更新。
如果大家都认为不需要for循环就可以做到。
mess = [{
"name": "user1",
"arrayOfJSON": `[{"email":"Alex@gmail","hobby":"coding"},{"email":"bob@gmail","hobby":"coocking"}]`
},
{
"name": "user2",
"arrayOfJSON": `[{"email":"Chris@gmail","hobby":"coding"},{"email":"bob@gmail","hobby":"coocking"}]`
},
{
"name": "user3",
"arrayOfJSON": `[{"email":"bob@gmail","hobby":"coocking"},{"email":"Alex@gmail","hobby":"coding"}]`
}
]
console.log(mess)
for (i = 0; i < mess.length; i++) {
console.log(JSON.parse(mess[i].arrayOfJSON))
for (m = 0; m < (JSON.parse(mess[i].arrayOfJSON)).length; m++) {
console.log("almost")
console.log((JSON.parse(mess[i].arrayOfJSON))[m])
}
}
答案 0 :(得分:0)
// Adapted from: https://gist.github.com/sphvn/dcdf9d683458f879f593
const traverse = function(o, fn, scope = []) {
for (let i in o) {
fn.apply(this, [i, o[i], scope]);
if (o[i] !== null && typeof o[i] === "object") {
traverse(o[i], fn, scope.concat(i));
}
}
}
const mess = [{
"name": "user1",
"arrayOfJSON": `[{"email":"Alex@gmail","hobby":"coding"},{"email":"bob@gmail","hobby":"coocking"}]`
}, {
"name": "user2",
"arrayOfJSON": `[{"email":"Chris@gmail","hobby":"coding"},{"email":"bob@gmail","hobby":"coocking"}]`
}, {
"name": "user3",
"arrayOfJSON": `[{"email":"bob@gmail","hobby":"coocking"},{"email":"Alex@gmail","hobby":"coding"}]`
}];
// Parse...
mess.forEach(item => {
if (item.arrayOfJSON) {
item.arrayOfJSON = JSON.parse(item.arrayOfJSON);
}
});
traverse(mess, (key, value, scope) => {
if (value === 'Alex@gmail') {
console.log(
`Position: mess[${scope.concat(key).map(k => isNaN(k) ? `'${k}'` : k).join('][')}]`
);
}
});
.as-console-wrapper {
top: 0;
max-height: 100% !important;
}
答案 1 :(得分:0)
mess = [{
"name": "user1",
"arrayOfJSON": `[{"email":"Alex@gmail","hobby":"coding"},{"email":"bob@gmail","hobby":"coocking"}]`
},
{
"name": "user2",
"arrayOfJSON": `[{"email":"Chris@gmail","hobby":"coding"},{"email":"bob@gmail","hobby":"coocking"}]`
},
{
"name": "user3",
"arrayOfJSON": `[{"email":"bob@gmail","hobby":"coocking"},{"email":"Alex@gmail","hobby":"coding"}]`
}
]
console.log(mess)
holdMessPosition = []
for (i = 0; i < mess.length; i++) {
var pos = (JSON.parse(mess[i].arrayOfJSON)).map(function(e) {
return e.email;
})
.indexOf("Alex@gmail");
console.log("user position is " + pos);
if (pos !== -1) {
holdMessPosition.push(i)
}
}
console.log(holdMessPosition)