現在、JavaScriptの問題で苦労しています。私は、元のオブジェクトと、私が望むプロパティへのパスの配列を渡すことによって、内に含まれるすべての変数だけでなく、複数レベルのプロパティを返すしたい。例えば複数レベルのプロパティとそのプロパティのフルパスへのアクセス
、私は次のオブジェクトがある場合:
getVarPath(obj, ["product.candidate.ID", "product.candidate.reference"])
そしてそれが渡された各変数を一つのオブジェクトを返します:
obj = {
product: {
candidate: {
id: 10,
reference: "test",
count: 4,
steps: 10
}
}
}
を私はメソッドを呼び出すことができるようにしたいです配列は、元の構造です。だから、これはそうのように見えるオブジェクトを返します:
{
product: {
candidate: {
id: 10,
reference: "test"
}
}
}
が、私は現時点では私の地元の溶液中で、この作業を持っている(1つの文字列ではなく、現時点では配列を渡します)。
現時点での解決策はかなり恐ろしいですが、私はそれを改善しようとしています。だれかがより良い方法を考えることができれば、それはすばらしいでしょう。 もう一度、これはかなり恐ろしいですが、私はそれを改善するために探しています。 ["product","candidate","ID"]
:var nestedElements="product.candidate.ID".split(.)"
これは、各レベルでの配列を返します。
まず、あなたが最初の文字列を分割することができます:入力配列の各要素について
var getVarPath = function(obj, keys){
var elements = keys.split("."),
evalStr = "",
objStr = "obj",
newObjStr = "newObj",
newObj = {};
if(elements.length > 1){
elements.forEach(function(key, index){
// first append a property accessor at the end of the eval string
evalStr = evalStr + "['" + key + "']";
// if we're at the last element, we've reached the value, so assign it
if(index === elements.length -1){
eval(newObjStr + evalStr + " = " + objStr + evalStr);
}
else {
// if we're not at the last, we're at an object level
// if the nested object doesn't exist yet, create it
if(!eval(newObjStr + evalStr)){
eval(newObjStr + evalStr + " = {};");
}
}
});
}
return newObj;
}
を、あなたは何を試してみましたこれまでのところ? –
私は現在の作業ソリューションで質問を編集しましたが、私はevalを使用していることが気に入らず、少し上手くしています。 – TomDavies